本文介绍了TypeError:列表索引必须是整数或切片,而不是str'转换字符'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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('-'))

想要:

1       2
     3
     4
     .... 20

输入2

想要:

1
      -
      3
      4...20

但是结果是:

推荐答案

执行:

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] = "-"

这里不需要.join(),因为无论如何您只想拥有一个字符.

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

您也可以像这样填写number列表:

You can also fill your number list like so:

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

这称为列表理解.

最后,如果您要打印完整列表,则只需执行print(number),而无需for循环.

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

如果要打印从索引xy的所有列表元素,可以使用列表切片:

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

number[3:15].

有关切片的更多示例,请参见此处.

See here for more examples of slices.

这篇关于TypeError:列表索引必须是整数或切片,而不是str'转换字符'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 07:39