简体   繁体   中英

TypeError: string indices must be integers - Python3

Problem

So, my problem is that I'm getting a TypeError: string indices must be integers , on this line: userCHR += str(user[i]) , but the code looks fine to me. Can someone help me?

Python Code

user = input("Please enter a string: ")
user = user.upper()

userCHR = ""

for i in user:
    userCHR += str(user[i])

print(userCHR)

If I'm not wrong, the i is already a string. Maybe you can try:

for i in user:
  userCHR += i

A for loop returns the character in the string, not the integer location, in Python.

From

userCHR += str(user[i])

To

userCHR += i

New Code

user = input("Please enter a string: ")
user = user.upper()

userCHR = ""

for i in user:
    userCHR += i

print(userCHR)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM