Remove all line breaks from a long string of text

前端 未结 8 1920
长发绾君心
长发绾君心 2020-11-28 19:53

Basically, I\'m asking the user to input a string of text into the console, but the string is very long and includes many line breaks. How would I take the user\'s string a

相关标签:
8条回答
  • 2020-11-28 20:47

    A method taking into consideration

    • additional white characters at the beginning/end of string
    • additional white characters at the beginning/end of every line
    • various end-line characters

    it takes such a multi-line string which may be messy e.g.

    test_str = '\nhej ho \n aaa\r\n   a\n '
    

    and produces nice one-line string

    >>> ' '.join([line.strip() for line in test_str.strip().splitlines()])
    'hej ho aaa a'
    

    UPDATE: To fix multiple new-line character producing redundant spaces:

    ' '.join([line.strip() for line in test_str.strip().splitlines() if line.strip()])
    

    This works for the following too test_str = '\nhej ho \n aaa\r\n\n\n\n\n a\n '

    0 讨论(0)
  • 2020-11-28 20:48

    You can try using string replace:

    string = string.replace('\r', '').replace('\n', '')
    
    0 讨论(0)
提交回复
热议问题