468,292 Members | 1,848 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,292 developers. It's quick & easy.

Removing the continous newline characters from the pythong string

Hi guys i m trying out newline characters and to clean them up
a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\nvvvv\n \n\n\nvsa\n\n\n\nasf
\n\nafs

hello guys

im trying to replace
\n\n\n\n\n\n\n\n\n with \n

thanks for help

\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n also with \n as the browser gives
\r carrriage returns

thanks for any help or pointers

May 1 '07 #1
3 1536
On 1 May 2007 14:30:12 -0700, mobil <mo************@gmail.comwrote:
Hi guys i m trying out newline characters and to clean them up
a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\nvvvv\n \n\n\nvsa\n\n\n\nasf
\n\nafs

hello guys

im trying to replace
\n\n\n\n\n\n\n\n\n with \n

thanks for help

\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n also with \n as the browser gives
\r carrriage returns

thanks for any help or pointers
Is this what you were looking for?
>>import re
message = '\n\r\n\r\n\n\nhello there\n\r\n!\n'
regex = re.compile('[\n\r]+')
regex.sub('\n', s)
'\nhello there\n!\n'

Ian
May 1 '07 #2
why not use split:
>>>s = " a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\nvvvv\n \n\n\nvsa\n\n\n\nasf... \n\nafs"
s.split()
['a', 'sss', 'vvvv', 'vsa', 'asf...', 'afs']
May 1 '07 #3
What was I thinking? split() will only work if you have no other
whitespace characters in the string. A regex like "[\n\r]+" is indeed
much more appropriate and robust.

Cheers
-Basilisk96

May 1 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.