replace function isn't working the it supposed to work

Question:

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']
Asked By: Sskatx

||

Answers:

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']
Answered By: Tim Biegeleisen

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

Answered By: tripleee

A simple list comprehension should suffice:

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

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
Answered By: Giuseppe La Gualano

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 != ' ']
Answered By: CamS
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.