Search code examples
pythonlistfor-loop

Error modifying a list to have its elements in lower case and spaces within an element changed to underscore (_)


I am trying to modify this list

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

so that the elements will be in lower case and spaces within the list replaced with an underscore '_'

I tried this:

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

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

print(usernames)

AND this error came up:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-96-513b68e18689> in <module>
      4 # write your for loop here
      5 for i in names:
----> 6     usernames = usernames.append(i.replace(" ", "_"))
      7 
      8 

AttributeError: 'NoneType' object has no attribute 'append'

Solution

  • You could replace the names in situ like this:

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

    ...or... if you want a new list then:

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