Python: Removing spaces from list objects [duplicate]

Strings in Python are immutable (meaning that their data cannot be modified) so the replace method doesn’t modify the string – it returns a new string. You could fix your code as follows:

for i in hello:
    j = i.replace(' ','')
    k.append(j)

However a better way to achieve your aim is to use a list comprehension. For example the following code removes leading and trailing spaces from every string in the list using strip:

hello = [x.strip(' ') for x in hello]

Leave a Comment