TypeError: string indices must be integers

忘是亡心i 2022-05-24 04:53 305阅读 0赞

1、错误描述

  1. >>> print(st[-1,-6]);
  2. Traceback (most recent call last):
  3. File "<pyshell#13>", line 1, in <module>
  4. print(st[-1,-6]);
  5. TypeError: string indices must be integers
  6. >>> print(st[-1,-5]);
  7. Traceback (most recent call last):
  8. File "<pyshell#14>", line 1, in <module>
  9. print(st[-1,-5]);
  10. TypeError: string indices must be integers
  11. >>> print(st[0,-2]);
  12. Traceback (most recent call last):
  13. File "<pyshell#15>", line 1, in <module>
  14. print(st[0,-2]);
  15. TypeError: string indices must be integers
  16. >>> print(st[0,-1]);
  17. Traceback (most recent call last):
  18. File "<pyshell#16>", line 1, in <module>
  19. print(st[0,-1]);
  20. TypeError: string indices must be integers
  21. >>> print(st[-1:-6]);
  22. >>>

2、错误原因

  1. st是字符串数据类型,可以使用“:”进行截取字符,但是上述实例中使用的是“,”,导致报错。但是,print(st\[-1:-6\])没有结果打印出来,这是为什么呢?
  2. >>> st="89kkkklkjlky6dyush";
  3. >>> st;
  4. '89kkkklkjlky6dyush'
  5. >>> print(st);
  6. 89kkkklkjlky6dyush

3、解决办法

  1. 调整截取字符的开始值和结束值
  2. >>> print(st[-1:-6]);
  3. >>> st[-1:-6];
  4. ''
  5. >>> st[-6:-1];
  6. '6dyus'
  7. >>>

发表评论

表情:
评论列表 (有 0 条评论,305人围观)

还没有评论,来说两句吧...

相关阅读