簡體   English   中英

字符串索引必須是整數-子字符串

[英]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索引是一個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
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM