2017-07-16 72 views
0

我打算获取长度字符串并让程序计数并显示在输入的字符串中找到的字母总数"T",但得到以下错误。第13行是这样的:if string[0,counter] == "T":字符串索引必须是整数 - 子字符串

有什么建议吗?

File "python", line 13, in TypeError: string indices must be integers

#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)) 

回答

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 
+0

感谢,使用索引计数器做到了。 – Cornel

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的数量给定字符串中

+0

谢谢。这样可行。 – Cornel

相关问题