Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace function isn't working the it supposed to work

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading