[英]Replacing one character with two (\n by \r\n ) replaces also one of the replacing characters
[英]Replacing “\r\n” with “\n”
我有一些文本数据打印出实际字符“\\r\\n”(总共四个字符)。 我想用单个“\\n”字符替换这四个字符,但我似乎无法让 Python 为我做这件事。 我目前正在尝试:
mytext.replace("\r\n", "\n")
但这只是打印出“\\n”(两个字符,而不是一个)。 我觉得我可能遗漏了一些明显的东西,但任何帮助将不胜感激。
我建议使用分割线而不是正则表达式或搜索/替换
"\n".join(mytext.splitlines())
mytext.replace(r"\r\n", r"\n")
'r' 表示一个原始字符串,它告诉 python 将文本中的反斜杠解释为文字字符而不是转义字符。
"\\n".join(mytext.splitlines())
这对我"\\n".join(mytext.splitlines())
。 mytext.replace(r"\\r\\n", r"\\n")
,这不起作用。
如果上述任何一项不起作用,这是一个尝试的解决方案(我使用 Python3 的 Anaconda Distribution 就是这种情况)。
mytext.replace("\\r\\n", "\\n")
这与 \\ 被用作转义字符有关。 我认为使用原始字符串格式化程序的上述答案会达到同样的目的,但无论出于何种原因对我都不起作用,而这确实如此。
抱歉,我误读了您的问题:
在这种情况下,您应该在字符串前加上 ar 以使用原始字符串:
mytext.replace(r"\r\n", r"\n")
当您将文件读取到变量时,python 会自动将 '\\r\\n' 转换为 '\\n',反之亦然。 但是如果你用“二进制模式”写回文件,那么python会将你的内容准确地写到文件中。 因此,只需将文件读取到变量并以二进制模式写回即可在 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")
如果您想使用 '\\r\\n' 作为换行符,只需更改LINEBREAK
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.