[英]String indices must be integers - substring
我想获得一个长度字符串,并进行程序计数,并显示在输入的字符串中找到的字母"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))
#Count the number of Ts in the string.
for counter in range(0,len(string)):
if string[0,counter] == "T":
numTs = numTs + 1
您的string
索引是一个tuple
: 0, 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
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数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.