Reputation: 178
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))
Upvotes: 0
Views: 319
Reputation: 11
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
Upvotes: 0
Reputation: 14619
#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
Upvotes: 1