0

I have a string which looks like this when I print it:

RT @HHRoadGuy: It's that time again! Time to tune in for the latest #fortheloveofmusic episode. Catch it now on @CMT!

http://t.co/VatlhGq9…

I tried to get rid of the linespacing with:

tweet = tweet.rstrip('\r\n')

But it does not work. Probably as the linespacing is inbetween. Also the replace function could not help. What can I do here?

2
  • the replace function could not help - In what way? What did you attempt? Commented Jul 11, 2013 at 11:26
  • You are absolutely right. Really stupid question. I just had a small error in my code. Sorry. tweet = tweet.replace('\n','') Commented Jul 11, 2013 at 11:30

5 Answers 5

1

Are you sure that the line delimeters are indeed '\r\n' and not just '\n'? Because replace() should work just fine:

>>> s = 'hello\r\n\r\nhi'
>>> print(s)
hello

hi
>>> s2 = s.replace('\r\n\r\n', '\r\n')
>>> print(s2)
hello
hi

Indeed, the rstrip() will not work, since that function only strips on the right (end) of the string.

Sign up to request clarification or add additional context in comments.

Comments

1

There are many line break characters: \n \n\r \r depending on the text input.

Look http://en.wikipedia.org/wiki/Newline, depending on your input text and replace that character

Comments

1

The following should work in most cases to get rid of all line breaks, regardless of how they're represented:

lines = tweet.splitlines()
tweet = " ".join(lines)

Or, to avoid double spacing (and adopting P.M.'s concept):

tweet = " ".join([line for line in lines if len(line)])

If you wanted to only get rid of blank lines but preserve line breaks:

tweet = "\n".join([line for line in lines if len(line)])

Comments

0
tweet = tweet.replace('\n','')

Is the answer. I just had a tiny error in my code and after trying all these different methods and things I got blind. Sorry!

Comments

0

Try this :

>>> '\n'.join([line for line in your_text.splitlines() if line.strip()])

See http://docs.python.org/2/library/stdtypes.html#str.splitlines for more informations on how it handles line breaks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.