![](/img/trans.png)
[英]How do I find and count all the occurrences of a substring in a string using only find and replace?
[英]i want to find number of occurrences of substring in string(without using count function) but i am getting wrong results
s="hellohel"
sub="hel"
count=0
for i in s:
if sub in s:
present = True
count+=1
else:
present = False
我得到 output:真 8 output 應該是:真 2
print(present,count)
您的代碼當前檢查hellohel中的每個字符是否在hellohel中。 就目前而言, hel總是在hellohel中,所以這將永遠是真的。 這意味着,您的計數實際上將計算hellohel中有多少個字符。
也許你正在尋找的是類似的東西
s = "hellohel"
sub = "hel"
count = 0
present = False
for i in range(len(s)):
if (s[i:i+len(sub)] == sub):
count += 1
present = True
print(count, present) # Prints 2 True
這段代碼需要稍微清理一下,並且可以進行一些優化。 但是,這應該有助於將您推向正確的方向。
所以它顯示的原因是因為 for 循環“for i in s:”,因為你的字符串有 8 個“hellohel”位置。 因此,每當您嘗試運行 for 循環時,它都會運行 8 次。
s="hellohel"
sub="hel"
count=0
for i in s: # this line iterates through each character the string "s" (8 times), assigning the current character to i
if sub in s: # this line is just checking whether "hel" is in "hellohel" once for every character in "hellohel"
present = True
count+=1 # that means it will count to 8 every time, because "hel" is always in "hellohel"
else:
present = False
總的來說,不是正確的方法。 這里有多個答案,use.count()、re,什么都沒有。 計算字符串中 substring 的出現次數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.