【问题标题】:Python string slicingPython 字符串切片
【发布时间】:2012-02-15 11:00:30
【问题描述】:

代码:

count = 0
oldcount = 0
for char in inwords:
    if char == " ":
        anagramlist.append(inwords[oldcount, count])
        oldcount = count
        count = 0
    else:
        count += 1

错误:

Traceback (most recent call last):
  File "C:/Users/Knowhaw/Desktop/Python Programs/Anagram solver/HTS anagram.py", line 14,        
in <module>
    anagramlist.append(inwords[oldcount, count])
TypeError: string indices must be integers

这到底是怎么回事? count 和 oldcount 显然是整数,但错误表明它们不是

我什至会写

anagramlist.append(inwords[int(oldcount), int(count)])

得到同样的错误

【问题讨论】:

  • 奇怪的标题把我拉到了这里……
  • 我可以看到如何将错误消息解释为暗示支持使用多个整数进行索引。 “字符串索引必须是整数”会更清楚。只是一个观察......
  • @chepner:对于初学者来说,它确实看起来令人困惑,但文档 [docs.python.org/tutorial/introduction.html] 足够清晰Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon. &gt;&gt;&gt; &gt;&gt;&gt; word[4] 'A' &gt;&gt;&gt; word[0:2] 'He' &gt;&gt;&gt; word[2:4] 'lp'
  • @chepner: 并且该消息还暗示(如果有人不知道)索引除了访问字符串中的单个符号之外还有其他用途

标签: python list indexing


【解决方案1】:

您正在尝试使用(oldcount, count) 作为列表的索引。这是一个元组,而不是一个 int。

你的意思是:

anagramlist.append(inwords[oldcount:count])

?

【讨论】:

    【解决方案2】:

    您的切片语法错误。代码:

    inwords[oldcount, count]
    

    解析为:

    inwords[(oldcount, count)]
    

    您不是从oldcount 切片到count,而是创建了一个oldcountcount 的元组并将其用作字符串索引。

    正确的 Python 切片语法是:

    inwords[oldcount:count]
    

    【讨论】:

      【解决方案3】:

      如果我理解您的代码,您可能正在尝试使用切片表示法,这需要使用:,而不是,。该逗号使解释器将您的代码理解为使用元组作为字符串的索引,这显然是不允许的。

      【讨论】:

        【解决方案4】:

        我认为(inwords[oldcount, count]) 有问题。您不能使用(oldcount, count) 作为索引。

        【讨论】:

          【解决方案5】:

          你只是想做anagramlist = inwords.split()吗?
          如果您真的想手动切片,则必须使用:

          anagramlist.append(inwords[oldcount:count+oldcount])
          

          【讨论】:

            猜你喜欢
            • 2014-07-21
            • 1970-01-01
            • 2013-10-29
            • 2020-11-27
            • 1970-01-01
            • 1970-01-01
            • 2021-05-01
            • 2014-12-04
            相关资源
            最近更新 更多