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