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]
Answer from Mark Byers on Stack OverflowStrings 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]
List comprehension [num.strip() for num in hello] is the fastest.
>>> import timeit
>>> hello = ['999 ',' 666 ']
>>> t1 = lambda: map(str.strip, hello)
>>> timeit.timeit(t1)
1.825870468015296
>>> t2 = lambda: list(map(str.strip, hello))
>>> timeit.timeit(t2)
2.2825958750515269
>>> t3 = lambda: [num.strip() for num in hello]
>>> timeit.timeit(t3)
1.4320335103944899
>>> t4 = lambda: [num.replace(' ', '') for num in hello]
>>> timeit.timeit(t4)
1.7670568718943969
How to remove extra space from output list tuple?
How to Remove Spaces From a String in Python (Complete 2026 Guide)
Remove brackets and appostrophes from the list
list - How to remove space from a title column in SharePoint online - SharePoint Stack Exchange
Hi everyone, I recently took the Fullstack Python Developer course and am now taking my first steps on this path.
Can you tell me what other methods of removing spaces from text you know and in which case, each of them is better to use?
So far I know 4 of them:
-
replace method -> text_wo_spaces = text.replace(" ","")
-
join and split methods -> text_wo_spaces = ' '.join(text.split())
-
list generator + join -> text_wo_spaces = ' '.join([char for char in text if char != ' '])
-
filter + join methods -> text_wo_spaces = ' '.join(filter(lambda char : != ' ', text))