Alex Mollberg
Alex Mollberg

Reputation: 231

Removing '\n' from list item

I have a list and the last list item has a \n which I don't want.

print(list)
[somebody,please,help\n]   #what I have


print(list)
[somebody,please,help]      #desired list

Upvotes: 0

Views: 3401

Answers (3)

mbowden
mbowden

Reputation: 714

str.strip() will remove the white space chars from the ends of the string. Don't forget that strip() returns a new string which needs to be assigned... You probably want.

for element in list:
    element = element.strip()

Upvotes: 0

blaffie
blaffie

Reputation: 505

You can use the strip function to remove any white space characters from the ends of the string for example:

str = str.strip()

So before printing, strip the string. Perhaps you can save the stripped strings in a new list.

Upvotes: 1

dyng
dyng

Reputation: 3054

I think your problem is like this.

As an answer :

list[-1] = list[-1].rstrip('\n')

Upvotes: 2

Related Questions