TypeError: list indices must be integers or slices, not str 'convert the chararter'

假装没事ソ 提交于 2020-01-22 03:48:04

问题


Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]    
for n in range(0, 20):
      print(Number[n]+1\n)
InputNum3 = input()
Number[InputNum3] = ''.join(str('-'))

want:

1       2
     3
     4
     .... 20

input 2

want:

1
      -
      3
      4...20

but the result is:

TypeError: list indices must be integers or slices, not str


回答1:


Do:

inputNum3 = int(input())

to get an Integer, you can't access lists by a String as index.

Your variable names should start with lowercase. Generally snakecase too, with all lowercase separated by underscore:

number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
input_num = int(input())
number[input_num] = "-"

You don't need the .join() here because you want to have just a single character anyway.

You can also fill your number list like so:

number = [x for x in range(20)]

This is called a list comprehension.

Lastly, you can just do print(number) if you want to print the full list, no need for the for loop.

If you want to print all list elements from index x to y you can use list slicing:

number[3:15] for example.

See here for more examples of slices.




回答2:


In Python3, input() returns a string. In Python2, however, input() returns the type you are looking for, an integer. Therefore, you need to cast the input() function to an int, since you are obviously trying to assign a value in the list by index.

Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]    
for n in range(0, 20):
   print(Number[n]+1\n)

InputNum3 = int(input())
Number[InputNum3] = ''.join(str('-'))



回答3:


Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]    
for n in range(0, 20):
      print(Number[n]+1\n)
>>InputNum3 = int(input())
Number[InputNum3] = ''.join(str('-'))

input function accept values as string.



来源:https://stackoverflow.com/questions/44372559/typeerror-list-indices-must-be-integers-or-slices-not-str-convert-the-charart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!