Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove '\n' from end of strings inside a list? [duplicate]

Tags:

python

I have 2 strings here:

line= ['ABDFDSFGSGA', '32\n']
line= ['NBMVA\n']

How do I remove \n from the end of these strings. I've tried rstrip() and strip() but I am still unable to remove the \n from the string. Can I have help removing it?

like image 631
rggod Avatar asked Jan 24 '14 05:01

rggod


1 Answers

You need to access the element that you want to strip from the list:

line= ['ABDFDSFGSGA', '32\n']

#We want to strip all elements in this list
stripped_line = [s.rstrip() for s in line]

What you might have done wrong, is to simply call line[1].rstrip(). This won't work, since the rstrip method does not work inplace, but returns a new string which is stripped.

Example:

>>> a = 'mystring\n'
>>> a.rstrip()
Out[22]: 'mystring'
>>> a
Out[23]: 'mystring\n'
>>> b = a.rstrip()
>>> b
Out[25]: 'mystring'
like image 60
Steinar Lima Avatar answered Oct 04 '22 22:10

Steinar Lima