Home > other >  replace function isn't working the it supposed to work
replace function isn't working the it supposed to work

Time:11-11

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']

CodePudding user response:

A simple list comprehension should suffice:

def str2list(argstr):
    return [c for c in argstr if c != ' ']

CodePudding user response:

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

CodePudding user response:

If you are open to using regex, you may try:

inp = "abc efg"
letters = re.findall(r'[a-z]', inp, flags=re.I)
print(letters)  # ['a', 'b', 'c', 'e', 'f', 'g']

You could also use:

inp = "abc efg"
output = list(inp.replace(" ", ""))
print(output)  # ['a', 'b', 'c', 'e', 'f', 'g']

CodePudding user response:

A very clean solution, without using libraries or replacements, is using List Comprehension.

The syntax of this tool is as follows:

[expression for item in iterable if condition == True]

so the code becomes:

def str2list(argstr):
    return [x for x in argstr if x != " "]

is the same thing, in a more compact way than the similar function you wrote, with an extra if statement:

def str2list(argstr):
    retlist = []
    for c in argstr:
        if c != " ":
            retlist.append(c)
    return retlist

CodePudding user response:

The easiest is to check if a character is a place if c == ' ' or see if it a character is not c != ' '

then you don't need to replace it. You're just changing a ' ' to a '' then adding it. you need to exclude it

def str2list(argstr):
    retlist = []
    for c in argstr:
        if c != " ":
            retlist.append(c)
    return retlist

This will fix your issue.

Or you could just use a comprehension

def str2list():
    return [c for c in argstr if c != ' ']
  • Related