2

I'm trying to find a really simple way of removing the white space in a list of strings. For I want to turn the list age:

age = ['15', '23 years', '21']

into

age = ['15', '23years', '21']

Notice how the space between '23' and 'years' was removed? I'm not sure why my if statement below doesn't work:

for x in age:
     x.replace(" ", "")

What am I missing here? I took a step back and tried to remove the whitespace from a simple string:

test = 'hi hi hi'

and the following code works for removing the whitespace:

test.replace(" ", "")

returning this when 'test is called:

'hihihi'

So why can't I just add a for loop to iterate over a list of strings and remove the whitespace like I did above? What code would allow me to solve my problem?

Thanks for your help!

1 Answers1

5

You need to modify the list, as str objects are immutable:

age = [x.replace(" ", "") for x in age]
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69