how to remove space characters (" ")in a list {PYTHON}
Question:
Im trying to write a for loop to remove space characters (" ") in my list but it’s just deleting some of the characters that are in the first of my lsit
this is my list
mylist=[" "," "," "," ","oho","abcd","1234",1234," "," ","omg"]
and this is my loop
for i in mylist:
if i==' ':
mylist.remove(i)
but when I print mylist I get this
[' ', 'oho', 'abcd', '1234', 1234, ' ', ' ', 'omg']
and I’m expecting this
['oho', 'abcd', '1234', 1234, 'omg']
Answers:
here is with list compehension:
mylist=[" "," "," "," ","oho","abcd","1234",1234," "," ","omg"]
new_list=[x for x in mylist if x != " "]
print(new_list) # prints ['oho', 'abcd', '1234', 1234, 'omg']
One way is to use str.isspace()
method:
[x for x in mylist if not str(x).isspace()]
#['oho', 'abcd', '1234', 1234, 'omg']
Reference: https://python-reference.readthedocs.io/en/latest/docs/str/isspace.html
Is this an XY problem ?
Just in case, if the reason you have such a list to begin with is that you were attempting to split a string while discarding all whitespace, but used str.split()
, you may want to try re.split
instead:
>>> import re
>>> data = ' oho abcd 1234 omg'
>>> re.split("s+", data.strip())
['oho', 'abcd', '1234', 'omg']
Im trying to write a for loop to remove space characters (" ") in my list but it’s just deleting some of the characters that are in the first of my lsit
this is my list
mylist=[" "," "," "," ","oho","abcd","1234",1234," "," ","omg"]
and this is my loop
for i in mylist:
if i==' ':
mylist.remove(i)
but when I print mylist I get this
[' ', 'oho', 'abcd', '1234', 1234, ' ', ' ', 'omg']
and I’m expecting this
['oho', 'abcd', '1234', 1234, 'omg']
here is with list compehension:
mylist=[" "," "," "," ","oho","abcd","1234",1234," "," ","omg"]
new_list=[x for x in mylist if x != " "]
print(new_list) # prints ['oho', 'abcd', '1234', 1234, 'omg']
One way is to use str.isspace()
method:
[x for x in mylist if not str(x).isspace()]
#['oho', 'abcd', '1234', 1234, 'omg']
Reference: https://python-reference.readthedocs.io/en/latest/docs/str/isspace.html
Is this an XY problem ?
Just in case, if the reason you have such a list to begin with is that you were attempting to split a string while discarding all whitespace, but used str.split()
, you may want to try re.split
instead:
>>> import re
>>> data = ' oho abcd 1234 omg'
>>> re.split("s+", data.strip())
['oho', 'abcd', '1234', 'omg']