How to remove \n and \r from a string

后端 未结 2 1783
灰色年华
灰色年华 2021-02-05 09:11

I currently am trying to get the code from this website: http://netherkingdom.netai.net/pycake.html Then I have a python script parse out all code in html div tags, and finally

相关标签:
2条回答
  • 2021-02-05 09:50

    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()
    
    0 讨论(0)
  • 2021-02-05 09:55

    yon use below

    to remove carriage return:

    • line = line.replace(r'\r', '') to remove tab
    • line = line.replace(r'\r', '')
    0 讨论(0)
提交回复
热议问题