如何以字符串大写形式生成单个字母

时间:2016-05-06 22:14:58

标签: python python-2.7

我正在尝试输入一个输入文本文件并使每个" i"这本身就是大写的。到目前为止,这是我的代码,但它创建了一长串代码,而不是保留换行符和段落。

with open("greenEggsAndHam.txt", "r") as myfile:
    iText = myfile.read().split()

oText = ''

for word in iText:
    if(word == "i"):
        word = word.upper()
    oText = oText + word + " "
print oText

输出现在是这样的:

I am Sam Sam I am That Sam-i-am!That Sam-i-am! I do not like that Sam-i-am!

而不是:

I am Sam
Sam I am

That Sam-i-am!
That Sam-i-am!
I do not like that Sam-i-am!

有没有办法在保留段落和换行符的同时做到这一点?

2 个答案:

答案 0 :(得分:2)

当您将文本拆分为一个大的单个单词列表时,您的代码会失败,因此会删除所有换行符,这就是为什么要留下一大行文本。

您可以在迭代文件对象时拆分每一行并检查i

with open("greenEggsAndHam.txt", "r") as myfile:
   for line in myfile:
       print(" ".join([w.upper() if w == "i" else w for w in line.split()]))

如果你想要一大块文字:

with open("greenEggsAndHam.txt", "r") as myfile:
   text = "\n".join([" ".join([ch.upper() if ch == "i" else ch for ch in line.split()]) for line in myfi

答案 1 :(得分:1)

Life

5
5
5
5
5
5
5
5
8
8
8
8
8
8

201504  201505  201506  201507  201508  201509  201510  201511  201512  201601  201602  201603