Mr. Elfman
Mr. Elfman

Reputation: 45

Python3 Remove \n from list

Helle @all!

I trying to remove \n characters from a list it looks like this: tryed a for loop:

for hotel in hotel_url_list:
    hotel.replace('\n', '')

it doesn't work! phyton3 prints:

['\n/hotel/at/alpen-adria-stadthotel.de.html?label=gen173nr-1FCAEoggJCAlhYSDNiBW5vcmVmaA6IAQGYAQfCAQp3aW5kb3dzIDEwyAEM2AEB6AEB-AELkgIBeagCAw;\n/sid=e812ccd62b87bc158a2175bdc410f874;ucfs=1;]

Thanks for your help!

Upvotes: 1

Views: 163

Answers (1)

timgeb
timgeb

Reputation: 78690

str.replace does not mutate the string (in fact, strings are immutable) but returns a new string. Therefore

hotel.replace('\n', '')

produces a new string which you immediately throw away because you don't have any reference to it.

An easy way to get what you want is to build a new list and reassign the name hotel_url_list.

hotel_url_list = [hotel.replace('\n', '') for hotel in hotel_url_list]

Upvotes: 3

Related Questions