简体   繁体   English

用“\\n”替换“\\r\\n”

[英]Replacing “\r\n” with “\n”

I have some text data that is printing out the actual characters "\\r\\n" (so four characters total).我有一些文本数据打印出实际字符“\\r\\n”(总共四个字符)。 I'd like to replace those four characters with the single "\\n" character, but I can't seem to make Python do it for me.我想用单个“\\n”字符替换这四个字符,但我似乎无法让 Python 为我做这件事。 I'm currently trying:我目前正在尝试:

mytext.replace("\r\n", "\n")

But that just prints out "\\n" (two characters, not one).但这只是打印出“\\n”(两个字符,而不是一个)。 I feel like I'm probably missing something obvious, but any help would be appreciated.我觉得我可能遗漏了一些明显的东西,但任何帮助将不胜感激。

我建议使用分割线而不是正则表达式或搜索/替换

"\n".join(mytext.splitlines())
mytext.replace(r"\r\n", r"\n")

'r' 表示一个原始字符串,它告诉 python 将文本中的反斜杠解释为文字字符而不是转义字符。

"\\n".join(mytext.splitlines()) This works for me. "\\n".join(mytext.splitlines())这对我"\\n".join(mytext.splitlines()) mytext.replace(r"\\r\\n", r"\\n") , this not work. mytext.replace(r"\\r\\n", r"\\n") ,这不起作用。

This is a solution to try if any of the above did not work (which was the case for me using the Anaconda Distribution of Python3).如果上述任何一项不起作用,这是一个尝试的解决方案(我使用 Python3 的 Anaconda Distribution 就是这种情况)。

mytext.replace("\\r\\n", "\\n")

This has to do with \\ being used as an escape character.这与 \\ 被用作转义字符有关。 I thought that the above answers that used the raw string formatter would achieve the same thing, but for whatever reason that did not work for me, and this did.我认为使用原始字符串格式化程序的上述答案会达到同样的目的,但无论出于何种原因对我都不起作用,而这确实如此。

Sorry, I misread your question:抱歉,我误读了您的问题:

In that case, you should prefix your string with ar to use raw strings:在这种情况下,您应该在字符串前加上 ar 以使用原始字符串:

mytext.replace(r"\r\n", r"\n")

python will auto convert '\\r\\n' to '\\n' when you read file to variable, and vice versa.当您将文件读取到变量时,python 会自动将 '\\r\\n' 转换为 '\\n',反之亦然。 But if you write back to file with "binary mode", then python will write exactly your content to file.但是如果你用“二进制模式”写回文件,那么python会将你的内容准确地写到文件中。 so simply read file to variable and write back with binary mode will auto convert '\\r\\n' to '\\n' in windows platform.因此,只需将文件读取到变量并以二进制模式写回即可在 Windows 平台中自动将 '\\r\\n' 转换为 '\\n'。

file_name = 'test.sh'
file_content = ''
with open(file_name) as f:
    file_content = f.read()

with open(file_name, 'wb') as f:
    f.write(file_content)

LINEBREAK = "\n"

with open(filename) as f:
    s = f.read()
    s = LINEBREAK.join(s.splitlines())
with open(new_filename, "wb") as f:
    f.write(s + "\n")

If you want to use '\\r\\n' as linebreak, just change the LINEBREAK .如果您想使用 '\\r\\n' 作为换行符,只需更改LINEBREAK

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

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