【问题标题】:Python Error string indices must be integers [duplicate]Python错误字符串索引必须是整数[重复]
【发布时间】:2021-09-20 12:42:12
【问题描述】:
def is_double_char(str):
  end = len(str)+1
  print(type(end))
  for i in range(1, len(str)): 
    add_one = i+1
    print(type(i))
    print(type(add_one))
    if  str[add_one, end].find(str[i]) != -1:
        return True
  return False

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

print(is_double_char("hello"))
______________________________
<class 'int'>
<class 'int'>
<class 'int'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-606a7223e550> in <module>()
----> 1 print(is_double_char("hello"))

<ipython-input-20-b1c815934cad> in is_double_char(str)
      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

TypeError: string indices must be integers

我不明白。从我的调试打印中,我所有的索引都已经是整数了。有人可以帮忙吗?谢谢。

【问题讨论】:

  • 但是add_one, end 不是整数。
  • 是的!我将其更改为 add_one:end,我的代码现在可以工作了。谢谢!

标签: python string typeerror


【解决方案1】:

代码:

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

输出:

hello: True
helo: False

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

【讨论】:

    【解决方案2】:

    也许这就是你需要的:

    def is_double_char(string):
      end = len(string)+1
      print(type(end))
      for i in range(1, len(string)): 
        add_one = i+1
        print(type(i))
        print(type(add_one))
        if  string[add_one: end].find(string[i]) != -1:
            return True
      return False
    

    注意:我将名为str 的变量更改为string,因为str 是一个内置类型。

    我将 , 替换为 :(第 8 行)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-16
      • 2014-12-30
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      相关资源
      最近更新 更多