Reputation: 2063
I would like to remove whitespace of the string of the list as following
original = ['16', '0000D1AE18', '1', '1', '1', 'S O S .jpg', '0']
after remove the whitespace
['16', '0000D1AE18', '1', '1', '1', 'SOS.jpg', '0']
Upvotes: 0
Views: 3153
Reputation: 12196
If you want to remove any whitespace (i.e.Space, Tab, CR and Newline), use this:
import re
without_spaces = [re.sub(r'\s+', '', item) for item in original]
If you need to replace only regular spaces, use the already suggested solution
without_spaces = [item.replace(' ', '') for item in original]
Upvotes: 1
Reputation: 1122082
Use str.translate()
on each element in a list comprehension:
[v.translate(None, ' ') for v in original]
Here None
means don't replace characters with other characters, and ' '
means remove spaces altogether. This produces a new list to replace the original.
The above only removes just the spaces. To remove all whitespace (newlines, tabs, feeds, etc.) simply expand what characters should be removed
[v.translate(None, ' \t\r\n\f\x0a') for v in original]
str.translate()
is the fastest option for removing characters from text.
Demo:
>>> original = ['16', '0000D1AE18', '1', '1', '1', 'S O S .jpg', '0']
>>> [v.translate(None, ' \t\r\n\f\x0a') for v in original]
['16', '0000D1AE18', '1', '1', '1', 'SOS.jpg', '0']
Upvotes: 6
Reputation: 1087
You can use
k=[]
for i in original :
j = i.replace(' ','')
k.append(j)
Upvotes: 0