Remove all newlines from inside a string

后端 未结 7 1889
自闭症患者
自闭症患者 2020-11-28 09:02

I\'m trying to remove all newline characters from a string. I\'ve read up on how to do it, but it seems that I for some reason am unable to do so. Here is step by step what

7条回答
  •  日久生厌
    2020-11-28 09:30

    Answering late since I recently had the same question when reading text from file; tried several options such as:

    with open('verdict.txt') as f: 
    

    First option below produces a list called alist, with '\n' stripped, then joins back into full text (optional if you wish to have only one text):

    alist = f.read().splitlines()
    jalist = " ".join(alist)
    

    Second option below is much easier and simple produces string of text called atext replacing '\n' with space;

    atext = f.read().replace('\n',' ')
    

    It works; I have done it. This is clean, easier, and efficient.

提交回复
热议问题