views:

175

answers:

5

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
+5  A: 

Solution via list comprehension:

>>> a = ['Hello ','everybody ','! ']
>>> [ e.strip() for e in a ]
['Hello', 'everybody', '!']

Documentation: string.strip / string.rstrip, string.lstrip respectively

The MYYN
`strip()` removes spaces from both ends of the string, to remove only trailing spaces `rstrip()` should be used (see my answer).
jetxee
+1  A: 
print [x.strip() for x in a]

This is called list comprehension

Kimvais
+9  A: 

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', '!']
jetxee
+1 for *r*strip()
Kimvais
+1  A: 

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.

Noufal Ibrahim
A: 
>>> a = ['Hello ','everybody ','! ']
>>> map(str.rstrip,a)
['Hello', 'everybody', '!']
>>> b = map(str.rstrip,a)
ghostdog74