【问题标题】:String indices must be integers - substring字符串索引必须是整数 - 子字符串
【发布时间】:2017-07-16 20:25:32
【问题描述】:

我想获取一个长度字符串并让程序计数并显示在输入的字符串中找到的字母 "T" 的总数,但出现以下错误。第 13 行是这样的:if string[0,counter] == "T":

有什么建议吗?

文件“python”,第 13 行,在 TypeError: 字符串索引必须是整数

#Variable to hold number of Ts in a string
numTs = 0

#Get a sentence from the user.
string = input("Enter a string: ")

#Count the number of Ts in the string.
for counter in range(0,len(string)):
  if string[0,counter] == "T":
    numTs = numTs + 1

#Display the number of Ts.
print("That string contains {} instances of the letter T.".format(numTs))

【问题讨论】:

    标签: python string for-loop


    【解决方案1】:
    #Count the number of Ts in the string.
    for counter in range(0,len(string)):
      if string[0,counter] == "T":
        numTs = numTs + 1
    

    string 的索引是 tuple0, counter

    您应该只使用索引counter

    for counter in range(0,len(string)):
      if string[counter] == "T":
        numTs = numTs + 1
    

    如果您的目标不仅仅是学习如何实现这样的算法,更惯用的方法是使用标准库的Counter

    >>> string = 'STack overflow challenge Topic'
    >>> from collections import Counter
    >>> c = Counter(string)
    >>> 
    >>> c['T']
    2
    

    【讨论】:

    • 谢谢,使用索引计数器做到了。
    【解决方案2】:
    string = input("Enter the string:\n");count = 0
    for chars in string:
        if chars == "T" or chars == "t":
            count = count + 1
    print ("Number of T's in the string are:",count)
    

    这将找到给定字符串中 t 的数量

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 2020-08-28
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      相关资源
      最近更新 更多