想要在每次看到目标变量时将计数器递增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")
您需要将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
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