Python 3 - TypeError: string indices must be integers / conditional statement

Python 3 - TypeError: string indices must be integers / conditional statement

我认为只要 if 语句为 True,那么 运行 代码行。为什么它在条件中想要一个整数?

#function that accepts a string and calculates the number of upper case and lower case

def case_count(str):
    total_cap_cases = 0
    total_low_cases = 0
    for words in str:
        if str[words].isupper():
            total_cap_cases += 1
        elif words.islower():
            total_low_cases += 1
        else:
            pass

    print(total_cap_cases)
    print(total_low_cases)


str = "How Many upper and LOWER case lettters are in THIS senTence?"
case_count(str)
str = "How Many upper and LOWER case lettters are in THIS senTence?"

def case_Counts(String):
print("Capital Letters: ", sum(1 for String in str if String.isupper()))
print("LowerCase Letters: ", sum(1 for String in str if String.islower()))

case_Counts(str)

您正在尝试使用 str 进行索引,但它的类型应该是 int

要修复它,您只需更改:

if str[words].isupper():

至:

if words.isupper():

我还建议在您的 str 上使用 replace(' ', ''),因为计算值时空格可能会计算在内。

您的代码有错误。你应该只使用 words.isupper(): 而不是 str[words].isupper()

def case_count(str): 
    total_cap_cases = 0 
    total_low_cases = 0 
    for words in str: 
        if words.isupper(): 
            total_cap_cases += 1 
        else: 
            total_low_cases += 1
    print(total_cap_cases)
    print(total_low_cases)

当我运行这段代码时:

s = "abc"

for words in s:
    print(words)

我得到这个输出:

$ python test.py
a
b
c

这是因为for variable in string:没有创建整数索引。相反,它一次将字符串的 个字符 分配给 variable, 个字符。

当您执行 for words in str: 时,您实际上是一次处理 str 个字符。你最好这样写:

for character in str:
    if character.isupper():
        tot_cap_cases += 1
    elif character.islower():
        tot_low_cases += 1
    else:
        tot_non_cases += 1

(此外,值得指出的是,在 unicode 世界中,您不能简单地假设任何不是大写的字符都必须是小写。根据 this Unicode FAQ page 大多数脚本在全部。)

您可以在 python 中迭代字符串,但字符串不是列表。 它的索引必须是整数,而不是 str

def case_count(string):
    total_cap_cases = 0
    total_low_cases = 0
    for words in string:
        if words.isupper():
            total_cap_cases += 1
        else:
            total_low_cases += 1

    print(total_cap_cases)
    print(total_low_cases)

def case_count(string):
    total_cap_cases = 0
    total_low_cases = 0
    for idx in range(0, len(string)):
        if string[idx].isupper():
            total_cap_cases += 1
        else:
            total_low_cases += 1

    print(total_cap_cases)
    print(total_low_cases)

另外,不要使用 str 作为变量。这是 python 关键字。