Home > Software design >  For loop with .replace()
For loop with .replace()

Time:07-23

I need to change the 'names' list to the 'username' form.

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
--> 
usernames = ["joey_tribbiani", "monica_geller", "chandler_bing", "phoebe_buffay"]

I wrote the code as below but it only outputs ["phoebe_buffay"]

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []


for name in names:
    names = name.replace(" ", "_").lower()
    usernames = names
    
    
print(usernames)

What is the problem?

CodePudding user response:

You can do it in one line:

usernames = [n.replace(" ", "_").lower() for n in names]

The problem is that usernames is always replaced in the loop. Try usernames.append(name.replace(" ", "_").lower()) instead

CodePudding user response:

You have to be careful with lists

The following code will work

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []


for name in names:
    usernames.append(name.replace(" ", "_").lower())


print(usernames)

CodePudding user response:

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
for name in names:
    usernames.append(name.replace(" ", "_").lower())
print(usernames)

CodePudding user response:

You need to use name instead of names and you don't have to assign a new value to usernames, you have to append a new item to the list instead.

Code

for name in names:
        name = name.replace(" ", "_").lower()
        usernames.append(name)

CodePudding user response:

Variables in python are pointers to an underlying object.

Problem

Initially you set usernames->[] and in each iteration of the for loop you set names->name.replace(" ", "_").lower().

In the last iteration that will evaluate to names->"phoebe_buffay". You then update usernames->names which evaulates to usernames->"phoebe_buffay"

Solution

Build up a new array in the for loop:

usernames = []
for name in names:
    usernames.append(name.replace(" ", "_").lower())

Using list comprehensions

Building up lists is exactly what python designed the list comprehension for:

usernames = [name.replace(" ", "_").lower() for name in names]

Using the map function

Alternatively you can use the map function to apply your 'mapping' to all elements:

usernames = list(map(lambda name: name.replace(" ", "_").lower(), names))

CodePudding user response:

You need to write usernames.append(names) in order to insert a name in the usernames array. Like following:

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []


for name in names:
    usernames.append(name.replace(" ", "_").lower())
    
    
print(usernames)

  • Related