需要修复(counter = counter + 1)错误[关闭]

问题描述 投票:-1回答:2

想要在每次看到目标变量时将计数器递增1,就会对counter = counter + 1产生错误

myString = input("Enter a string \n")
target = input("enter the target variable\n")

length = len(myString)

for j in range(length):
    if myString[j] == target:
        counter = counter + 1
print(target, "occured", count, "times")
python increment
2个回答
1
投票

您需要将counter初始化为0,如下所示:

counter = 0

myString = input("Enter a string \n")
target = input("enter the target variable\n")
length = len(myString)

for j in range(length):
    if myString[j] == target:
        counter = counter + 1
print(target, "occured", counter, "times")

因此,如果字符串是hello,目标变量是l

输出将是:l occured 2 times


1
投票

Pythonic解决这个问题的方法是在字符串target中查找myString变量,然后在找到它时递增counter。比较应该不区分大小写,以获得准确的结果。使用lower()将字符串和目标变量转换为小写。

myString = input("Enter a string \n")
target = input("enter the target variable\n")

count = 0
for j in myString:
    if target.lower() in j.lower():
        count += 1
print(target, "occurred", count, "times")
#Output:
Enter a string 
The combinations of ABC are ABC,BAC,CAB
enter the target variable
b
b occurred 5 times
© www.soinside.com 2019 - 2024. All rights reserved.