在 Python 2.7 中替换字符串中的 '\n'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29251378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace '\n' in a string in Python 2.7
提问by
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 ' $ '. I just used:
我想将 newLine '\n' 转换为 ' $ '。我刚用过:
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.
谢谢你。
采纳答案by enrico.bacis
It is possible that your newlines are represented as \r\n
. In order to replace them you should do:
您的换行符可能表示为\r\n
. 为了替换它们,您应该执行以下操作:
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'
回答by Padraic Cunningham
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'