python – Remove all line breaks from a long string of text

python – Remove all line breaks from a long string of text

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 didnt 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 youre 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 Id avoid but would love to use sometimes: file. For the same reason.

You can try using string replace:

string = string.replace(r, ).replace(n, )

python – Remove all line breaks from a long string of text

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(nnsome    text rn with multiple whitespace.split())
Out: some text with multiple whitespace

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

Leave a Reply

Your email address will not be published.