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?
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?
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'
The type of line is list, so you cannot apply any of the strip
methods. The strip methods is for strings.
There you need to iterate over the list and apply rstrip()
method on each string present in that list.
>>> line= ['ABDFDSFGSGA', '32\n']
>>> map(str.rstrip, line)
['ABDFDSFGSGA', '32']
You can use a .replace('\n','')
but just note that this will delete all instances of \n
If you want to do this for entire list you could just do:
line = [i.replace('\n','') for i in line]