Can't delete “\\r\\n” from a string

若如初见. 提交于 2019-12-06 08:57:08

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).

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", "").

You can see the list of escape sequences Python supports in the String and Byte Literals subsection of the Lexical Analysis section in the Python Language Reference.

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]
>>> my_string = "la lala 135 1039 921\r\n"
>>> my_string.rstrip()
'la lala 135 1039 921'

Alternate solution with just slicing off the end, which works better with the bytes->string situation:

>>> my_string = b"la lala 135 1039 921\r\n"
>>> my_string = my_string.decode("utf-8")
>>> my_string = my_string[0:-2]
>>> my_string
'la lala 135 1039 921'

Or hell, even a regex solution, which works better:

re.sub(r'\r\n', '', my_string)

You could also determine the length of the string say 20 characters then truncate it to 18 regardless of the last two characters or verify they are the characters before you do that. Sometimes it helps to compare the ascii value first pseudo logic:

if last character in string is tab, cr, lf or ? then shorten the string by one. Repeat till you no longer find ending characters matching tab, cr, lef, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!