python TypeError: str object does not support item assignment

created at 06-30-2021 views: 19


When doing an exercise question, the topic is: 

Use the map() function to change the irregular English name entered by the user into capitalized first letters, and other canonical names in lowercase.

When writing at the beginning, capitalize the first letter directly as name[0] = name[0].upper()

then I got this error

TypeError:'str' object does not support item assignment

reason and solution

The reason is: In python, strings are immutable objects and cannot be directly assigned and modified by subscripts. The same immutable objects include numbers, strings, and tuples.

So the solution for this question should be

def normalize(name):
    return name[0].upper() + name[1:len(name)].lower()

# test code
L1 = ['liLEi', 'HAnMeimEI']
L2 = list(map(normalize, L1))


['Lilei', 'Hanmeimei']
created at:06-30-2021
edited at: 06-30-2021: