Hello guys I’m trying to create a function that returns a list out of a string ((((Without the space))))
I’m using the replace function to remove the space however I’m still getting a space
def str2list(argstr):
retlist = []
for c in argstr:
c=c.replace(" ", "")
retlist.append(c)
return retlist
print(str2list('abc efg'))
```
`
output:['a', 'b', 'c', '', 'e', 'f', 'g']
desired output:['a', 'b', 'c', 'e', 'f', 'g']
>Solution :
You are replacing spaces with empty strings, where you would like to remove them from the list entirely. Think about what happens when the loop sees " ".
The simple fix is instead to not append spaces.
def str2list(argstr):
retlist = []
for c in argstr:
if c != " ":
retlist.append(c)
return retlist
print(str2list('abc efg'))
Somewhat more elegantly, try
def str2list(argstr):
return [c for c in argstr if c != " "]
(Thanks to @Cobra for the improved implementation; I had a clumsy lambda at first.)