s="hellohel"
sub="hel"
count=0
for i in s:
if sub in s:
present = True
count =1
else:
present = False
我得到輸出:True 8 輸出應該是:True 2
print(present,count)
uj5u.com熱心網友回復:
您的代碼當前檢查hellohel 中的每個字符,如果hel位于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
這段代碼需要稍微清理一下,還有一些優化可以做。但是,這應該有助于將您推向正確的方向。
uj5u.com熱心網友回復:
所以它顯示的原因是因為for回圈“for i in s:”,因為你的字串有8個“hellohel”位置。因此,每當您嘗試運行 for 回圈時,它都會運行 8 次。
uj5u.com熱心網友回復:
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
總的來說,這不是接近它的正確方法。這里有多個答案不使用 .count() 而是使用 re,或者除了 vanilla python 什么都沒有。計算字串中子字串出現的次數
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399337.html
上一篇:如何讓virtualenv在Ubuntu上看到默認的python版本
下一篇:Python子行程回圈運行兩次
