python - 如何将字符串中的单个字母变成大写

标签 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!

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

最佳答案

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

您可以在迭代文件对象时分割每一行并检查 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

关于python - 如何将字符串中的单个字母变成大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37082185/

相关文章:

python - 检查两个字典是否不相交

python - 如何使用 Pyramid(Python 框架)模拟 mod_rewrite 的 url 别名功能?

python - 寻找一种方法来删除重复的答案

python-2.7 - Python >> matplotlib : Get the number of lines on a current plot?

python - 匹配两个 Python 列表的长度

python - sqlalchemy 创建不带命名关键字的插入对象

python - 用于通过解析器中的参数从特定模型中删除数据的 BaseCommand

python - matplotlib 堆积面积图中的动态标签

python - 多个 python 版本和解释器

python - python 中的 next() 真的那么快吗?