字符串索引必须是整数 - substring

时间:2017-07-16 20:25:32

标签: python string for-loop

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

有什么建议吗?

  

File" python",第13行,in   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))

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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的数量