python - 无法从字符串中删除 "\r\n"

标签 python string python-3.x replace strip

我有这样一个字符串:

la lala 135 1039 921\r\n

而且我无法删除 \r\n

最初这个字符串是一个字节对象,但后来我把它转换成了字符串

我尝试使用 .strip("\r\n").replace("\r\n", "") 但没有...

最佳答案

>>> my_string = "la lala 135 1039 921\r\n"
>>> my_string.rstrip()
'la lala 135 1039 921'

仅切掉末尾的替代解决方案,它更适合 bytes->string 情况:

>>> 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'

或者 hell ,即使是正则表达式解决方案,效果更好:

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

关于python - 无法从字符串中删除 "\r\n",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45383938/

相关文章:

c# - 数据表选择 : Expression with a space problem

python - python-3中的 '%% time'是什么意思?

python - 名称错误 'html' 未使用 beautifulsoup4 定义

python - PyQt Web 套件 Qwebview 的默认用户代理是什么以及如何获取它

python - 如何将负数转换为正数?

Python 参数解析

string - 为什么从标准输入读取用户输入时我的字符串不匹配?

python - 将 "letter number"(国际象棋位置)的列表分成单独的列表

Char 等于 C 中的 char 变量

python - Pandas 用 groupby 划分两列