how to remove white spaced from a nested list
Beginner Question: Removing all substrings from string between two characters.
What is the difference between Remove All Spaces and Remove All Whitespace?
How do I remove extra spaces from text?
When should I use this whitespace cleaner?
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]
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
hi, I have made a list already but wanted to remove the blank spaces from each index of my nested list. the list is pretty long so I will add a small version of it below.
list1 = [[' CITS2224-1 ', ' CITS2023-2 ', ' CITS3221-2 ', ' CITS3224-1 ', ' CITS3225-1 '], [' CITS2023-2 ', ' ENSC3221-2 ', ' ENSC3224-1 ', ' ENSC3225-1 ', ' ENSC3227-2 ', ' ENSC3210-1 ', ' ENSC3221-1 ', ' MECH3023-2 '], [' CITS1021-2 ', ' CITS2021-1 ', ' CITS2023-2 ', ' ENSC2224-1 ', ' ENSC3211-2 ', ' ENSC3213-2 ', ' MATH2221-1 ', ' STAT1524-1 ']
there is a space in front and after each index of the string and I want to remove it. for example the first index being 'CITS224-1'. I have tried looping through the entire list and using the replace function however that is messing with the design of the list. I want to leave the way that the list is nested untouched only want to remove the blank space before and after
thanks for any help