Python 3 - TypeError:字符串索引必须是整数/条件语句



我认为只要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)

当我运行此代码时:

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 世界中,您不能简单地假设任何非大写字符都必须是小写的。根据这个 Unicode 常见问题解答页面,大多数脚本根本没有大小写。

代码中存在错误。你应该只使用 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)

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

要修复它,您只需更改:

if str[words].isupper():

自:

if words.isupper():

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

你可以在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关键字。

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)

最新更新