Hello everybody!
How can i cut off the last empty space?
a = ['Hello ','everybody ','! ']
for i in range(len(a)):
a[i,-1]=''
print a
Hello everybody!
How can i cut off the last empty space?
a = ['Hello ','everybody ','! ']
for i in range(len(a)):
a[i,-1]=''
print a
Solution via list comprehension:
>>> a = ['Hello ','everybody ','! ']
>>> [ e.strip() for e in a ]
['Hello', 'everybody', '!']
Documentation: string.strip
/ string.rstrip
, string.lstrip
respectively
To cut off only last (right) empty spaces, use rstrip()
method. strip()
removes spaces from both ends:
>>> s = " abc "
>>> s.rstrip()
' abc'
>>> s.strip()
'abc'
In your example:
>>> [s.rstrip() for s in ['Hello ','everybody ','! '] ]
['Hello', 'everybody', '!']
The list comprehension approaches mentioned above would be the Pythonic way to solve this problem but they don't alter the list itself (ie. a). If you want to change those, you'll have to iterate as you've done over the list and instead of your assignment do an
a[i] = a[i].rstrip() # For stripping off trailing whitespaces only.
This is of course, bad style and I would recommend the list comprehension based method as well.
>>> a = ['Hello ','everybody ','! ']
>>> map(str.rstrip,a)
['Hello', 'everybody', '!']
>>> b = map(str.rstrip,a)