python错误字符串索引必须是整数

ax6ht2ek  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(436)

此问题已在此处找到答案

理解切片表示法(33个答案)
10小时前关门了。

  1. def is_double_char(str):
  2. end = len(str)+1
  3. print(type(end))
  4. for i in range(1, len(str)):
  5. add_one = i+1
  6. print(type(i))
  7. print(type(add_one))
  8. if str[add_one, end].find(str[i]) != -1:
  9. return True
  10. return False

这是我的密码。该方法应查找字符串是否包含2个或更多相同字符。

  1. print(is_double_char("hello"))
  2. ______________________________
  3. <class 'int'>
  4. <class 'int'>
  5. <class 'int'>
  6. ---------------------------------------------------------------------------
  7. TypeError Traceback (most recent call last)
  8. <ipython-input-21-606a7223e550> in <module>()
  9. ----> 1 print(is_double_char("hello"))
  10. <ipython-input-20-b1c815934cad> in is_double_char(str)
  11. 6 print(type(i))
  12. 7 print(type(add_one))
  13. ----> 8 if str[add_one, end].find(str[i]) != -1:
  14. 9 return True
  15. 10 return False
  16. TypeError: string indices must be integers

我不明白。根据我的调试打印,我的所有索引都已经是整数了。有人能帮忙吗?非常感谢。

rqcrx0a6

rqcrx0a61#

代码:

  1. def is_double_char(str):
  2. end = len(str)+1
  3. for i in range(1, len(str)):
  4. add_one = i+1
  5. if str[add_one:end].find(str[i]) != -1:
  6. return True
  7. return False
  8. print(f'hello: {is_double_char("hello")}')
  9. print(f'helo: {is_double_char("helo")}')

输出:

  1. hello: True
  2. helo: False

我做的唯一修改就是你拼接列表的方式。此外,使用 str 作为输入参数的名称是一种非常糟糕的做法。尝试使用stru输入之类的东西。

展开查看全部
bnl4lu3b

bnl4lu3b2#

也许这就是你需要的:

  1. def is_double_char(string):
  2. end = len(string)+1
  3. print(type(end))
  4. for i in range(1, len(string)):
  5. add_one = i+1
  6. print(type(i))
  7. print(type(add_one))
  8. if string[add_one: end].find(string[i]) != -1:
  9. return True
  10. return False

注意:我更改了名为 str 具有 string 因为 str 是一种内置类型。
我换了 , 具有 : (第8行)。

相关问题