问题描述
我有一个这样的字符串:
I have a string like this:
la lala 135 1039 921\r\n
而且我无法删除 \r\n
.
最初这个字符串是一个字节对象,但后来我将它转换为字符串
Initially this string was a bytes object but then I converted it to string
我尝试使用 .strip("\r\n")
和 .replace("\r\n", "")
但什么都没有...
I tried with .strip("\r\n")
and with .replace("\r\n", "")
but nothing...
推荐答案
问题是该字符串包含一个文字反斜杠后跟一个字符.通常,当写入诸如 .strip("\r\n")
之类的字符串时,这些会被解释为转义序列,其中 "\r"
表示一个回车返回(ASCII 表中的 0x0D)和 \n"
表示换行(0x0A).
The issue is that the string contains a literal backslash followed by a character. Normally, when written into a string such as .strip("\r\n")
these are interpreted as escape sequences, with "\r"
representing a carriage return (0x0D in the ASCII table) and "\n"
representing a line feed (0x0A).
因为 Python 将反斜杠解释为转义序列的开头,所以您需要在它后面加上另一个反斜杠以表示您的意思是字面反斜杠.因此,调用需要 .strip("\\r\\n")
和 .replace("\\r\\n", "")代码>.
Because Python interprets a backslash as the beginning of an escape sequence, you need to follow it by another backslash to signify that you mean a literal backslash. Therefore, the calls need to be .strip("\\r\\n")
and .replace("\\r\\n", "")
.
注意:你真的不想在这里使用 .strip()
因为它影响的不仅仅是字符串的结尾,因为它会删除反斜杠和字母r";和n"从字符串..replace()
在这里好一点,因为它会匹配整个字符串并替换它,但它也会匹配字符串中间的 \r\n
,不只是结束.删除序列的最直接方法是下面给出的条件.
Note: you really don't want to use .strip()
here as it affects a lot more than just the end of the string as it will remove backslashes and the letters "r" and "n" from the string. .replace()
is a little better here in that it will match the whole string and replace it, but it will match \r\n
in the middle of the string too, not just the end. The most straight-forward way to remove the sequence is the conditional given below.
您可以在 Python 语言参考中词法分析部分的字符串和字节文字小节.
就其价值而言,我不会使用 .strip()
来删除序列..strip()
删除字符串中的所有字符(它将字符串视为一个集合,而不是模式匹配)..replace()
将是一个更好的选择,或者当您检测到它存在时,简单地使用切片符号从字符串中删除尾随的 "\\r\\n"
:
For what it's worth, I would not use .strip()
to remove the sequence. .strip()
removes all characters in the string (it treats the string as a set, rather than a pattern match). .replace()
would be a better choice, or simply using slice notation to remove the trailing "\\r\\n"
off the string when you detect it's present:
if s.endswith("\\r\\n"):
s = s[:-4]
这篇关于无法删除“\r\n"从一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!