需要修复(计数器=计数器+ 1)错误

时间:2019-04-25 19:31:01

标签: python increment

希望每次看到目标变量时计数器不断增加错误,因为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")

2 个答案:

答案 0 :(得分: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 :(得分:1)

解决此问题的Python方法是在字符串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