python - clear newlines in several texts with list comprehension doesn't work -


i'd replace newlines ('\r\n') whitespace(' ') in several texts using list comprehension. tried following:

url1 = 'https://www.gutenberg.org/files/345/345.txt' dracula = urllib2.urlopen(url1).read()  url2 = 'https://www.gutenberg.org/cache/epub/18223/pg18223.txt' buddhism = urllib2.urlopen(url2).read()  url3 = 'https://www.gutenberg.org/files/14776/14776.txt' horses = urllib2.urlopen(url3).read()  texte = [dracula, buddhism, horses] texte = [text.replace('\r\n', ' ') text in texte] 

--> doesn't work - newlines ('\r\n') still there!

but same kind of code more simple list of texts worked:

text1 = "23482304 \r\nd34\r\n\r\n" text2 = "\r\nas doi\r\nuas \r\n ou" text3 = "trolo\r\nlol"  liste = [text1, text2, text3]  liste = [i.replace("\r\n", " ") in liste] 

--> newlines replaced!

  • does have idea went wrong?

the str.replace method returns new object , need re assign main object if want change :

>>> text1 = "23482304 \r\nd34\r\n\r\n" >>> text2 = "\r\nas doi\r\nuas \r\n ou" >>> text3 = "trolo\r\nlol" >>>  >>> liste = [text1, text2, text3] >>>  >>> liste = [i.replace("\r\n", " ") in liste] >>> liste ['23482304  d34  ', ' doi uas   ou', 'trolo lol'] >>> text1 '23482304 \r\nd34\r\n\r\n' 

also since strings immutable can not modify them using list comprehension or changing copy of them need change them directly :

for example :

>>> text1 = "23482304 \r\nd34\r\n\r\n" >>> text1=text1.replace("\r\n", " ") >>> text1 '23482304  d34  ' 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -