Remove all line breaks from a long string of text

前端 未结 8 1919
长发绾君心
长发绾君心 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:30

    updated based on Xbello comment:

    string = my_string.rstrip('\r\n')
    

    read more here

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

    How do you enter line breaks with raw_input? But, once you have a string with some characters in it you want to get rid of, just replace them.

    >>> mystr = raw_input('please enter string: ')
    please enter string: hello world, how do i enter line breaks?
    >>> # pressing enter didn't work...
    ...
    >>> mystr
    'hello world, how do i enter line breaks?'
    >>> mystr.replace(' ', '')
    'helloworld,howdoienterlinebreaks?'
    >>>
    

    In the example above, I replaced all spaces. The string '\n' represents newlines. And \r represents carriage returns (if you're on windows, you might be getting these and a second replace will handle them for you!).

    basically:

    # you probably want to use a space ' ' to replace `\n`
    mystring = mystring.replace('\n', ' ').replace('\r', '')
    

    Note also, that it is a bad idea to call your variable string, as this shadows the module string. Another name I'd avoid but would love to use sometimes: file. For the same reason.

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

    You can split the string with no separator arg, which will treat consecutive whitespace as a single separator (including newlines and tabs). Then join using a space:

    In : " ".join("\n\nsome    text \r\n with multiple whitespace".split())
    Out: 'some text with multiple whitespace'
    

    https://docs.python.org/2/library/stdtypes.html#str.split

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

    Another option is regex:

    >>> import re
    >>> re.sub("\n|\r", "", "Foo\n\rbar\n\rbaz\n\r")
    'Foobarbaz'
    
    0 讨论(0)
  • 2020-11-28 20:44

    The problem with rstrip is that it does not work in all cases (as I myself have seen few). Instead you can use - text= text.replace("\n"," ") this will remove all new line \n with a space.

    Thanks in advance guys for your upvotes.

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

    If anybody decides to use replace, you should try r'\n' instead '\n'

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