简体   繁体   English

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

[英]String indices must be integers - substring

I'm tying to get a length string and have the program count and display the total number of letter "T" found in the entered string but getting the following error. 我想获得一个长度字符串,并进行程序计数,并显示在输入的字符串中找到的字母"T"的总数,但出现以下错误。 Line 13 is this: if string[0,counter] == "T": 第13行是这样的: if string[0,counter] == "T":

Any suggestions? 有什么建议么?

File "python", line 13, in TypeError: string indices must be integers 文件“ 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

Your index for string is a tuple : 0, counter . 您的string索引是一个tuple0, counter

Instead you should just use the index counter . 相反,您应该只使用索引counter

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

If your goal is not merely to learn how to implement algorithms like this, a more idiomatic way is to use the standard library's Counter . 如果您的目标不仅仅是学习如何实现这样的算法,那么更惯用的方法是使用标准库的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)

This will find the number of t's in the given string 这将找到给定字符串中的t数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM