简体   繁体   English

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

[英]Replace '\n' in a string in Python 2.7

This is my file.txt:这是我的文件.txt:

Egg and Bacon;
Egg, sausage and Bacon
Egg and Spam;
Spam Egg Sausage and Spam;
Egg, Bacon and Spam;

I wanna convert the newLine '\\n' to ' $ '.我想将 newLine '\\n' 转换为 ' $ '。 I just used:我刚用过:

f = open(fileName)
text = f.read()      
text = text.replace('\n',' $ ')
print(text)

This is my output:这是我的输出:

$ Spam Egg Sausage and Spam;

and my output must be like:我的输出必须是这样的:

Egg and Bacon; $ Egg, sausage and Bacon $ Egg ...

What am I doing wrong?我究竟做错了什么? I'm using #-*- encoding: utf-8 -*-我正在使用#-*- encoding: utf-8 -*-

Thank you.谢谢你。

It is possible that your newlines are represented as \\r\\n .您的换行符可能表示为\\r\\n In order to replace them you should do:为了替换它们,您应该执行以下操作:

text.replace('\r\n', ' $ ')

For a portable solution that works on both UNIX-like systems (which uses \\n ) and Windows (which uses \\r\\n ), you can substitute the text using a regex:对于适用于类 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'

You can use splitlines.您可以使用分割线。

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;

Or simply use rstrip and join on the file object without reading all into memory:或者简单地使用 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;

Which is a much more efficient solution than reading all the file into memory and using a regex.这是比将所有文件读入内存并使用正则表达式更有效的解决方案。 You should also always use with to open your files as it closes them automatically.您还应该始终使用with打开您的文件,因为它会自动关闭它们。

rstrip will remove \\n \\r\\n etc.. 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', '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM