在 Python 2.7 中替换字符串中的 '\n'

Replace '\n' in a string in Python 2.7

这是我的file.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 ...

我做错了什么?我正在使用 #-*- encoding: 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'

您可以使用分割线。

lines = """Egg and Bacon;
Egg, sausage and Bacon
Egg and Spam;
Spam Egg Sausage and Spam;
Egg, Bacon and Spam;"""

print(" $ ".join(lines.splitlines()))
Egg and Bacon; $ Egg, sausage and Bacon $ Egg and Spam; $ Spam Egg Sausage and Spam; $ Egg, Bacon and Spam;

或者简单地使用 rstrip 并加入文件对象而不将所有内容读入内存:

with open("in.txt") as f: 
    print(" $ ".join(line.rstrip() for line in f))
    Egg and Bacon; $ Egg, sausage and Bacon $ Egg and Spam; $ Spam Egg Sausage and Spam; $ Egg, Bacon and Spam;

这是比将所有文件读入内存并使用正则表达式更有效的解决方案。您还应该始终使用 with 打开您的文件,因为它会自动关闭它们。

rstrip 将删除 \n \r\n 等..

In [41]: s = "foo\r\n"
In [42]: s.rstrip()
Out[42]: 'foo'    
In [43]: s = "foo\n"    
In [44]: s.rstrip()
Out[44]: 'foo'
text = text.replace('\n', '')