简体   繁体   中英

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. Line 13 is this: if string[0,counter] == "T":

Any suggestions?

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

Instead you should just use the index 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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