5

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?

Steinar Lima
  • 7,644
  • 2
  • 39
  • 40
rggod
  • 611
  • 5
  • 11
  • 19

3 Answers3

13

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'
Steinar Lima
  • 7,644
  • 2
  • 39
  • 40
6

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']
Sayan Chowdhury
  • 419
  • 4
  • 13
5

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]
aidnani8
  • 2,057
  • 1
  • 13
  • 15