这是我的文件.txt:
Egg and Bacon;
Egg, sausage and Bacon
Egg and Spam;
Spam Egg Sausage and Spam;
Egg, Bacon and Spam;
我想将换行符 '\n' 转换为 ' $ '。我刚刚用过:
f = open(fileName)
text = f.read()
text = text.replace('\n',' $ ')
print(text)
这是我的输出:
$ Spam Egg Sausage and Spam;
我的输出必须是这样的:
Egg and Bacon; $ Egg, sausage and Bacon $ Egg ...
我做错了什么?我正在使用 #-*- 编码:utf-8 -*-
谢谢。
最佳答案
您的换行符可能表示为 \r\n
。为了替换它们,您应该这样做:
text.replace('\r\n', ' $ ')
对于同时适用于类 UNIX 系统(使用 \n
)和 Windows(使用 \r\n
)的可移植解决方案,您可以替换为使用正则表达式的文本:
>>> import re
>>> re.sub('\r?\n', ' $ ', 'a\r\nb\r\nc')
'a $ b $ c'
>>> re.sub('\r?\n', ' $ ', 'a\nb\nc')
'a $ b $ c'
关于string - 在 Python 2.7 中替换字符串中的 '\n',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29251378/