How to remove \\n and \\r from a string

泪湿孤枕 提交于 2019-12-04 02:13:26

A simple solution is to strip trailing whitespace:

with open('gash.txt', 'r') as var:
    for line in var:
        line = line.rstrip()
        print(line)

The advantage of rstrip() over using a [:-2] slice is that this is safe for UNIX style files as well.

However, if you only want to get rid of \r and they might not be at the end-of-line, then str.replace() is your friend:

line = line.replace('\r', '')

If you have a byte object (that's the leading b') the you can convert it to a native Python 3 string using:

line = line.decode()

One simple solution is just to strip off the last two characters of each line:

f = open('yourfile')
for line in f.readlines():
  line = line[:-2] # Removes last two characters (\r\n)
  print(repr(line))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!