![](/img/trans.png)
[英]str.find() = TypeError: unsupported operand type(s) for +: 'int' and 'str' ..?
[英]str.find(s) fails if str starts with s
此代碼應該計算字符串 s 中 'bob' 的出現次數。 如果 s 不以 'bob' 開頭,則代碼工作正常,我正在尋找計數。 但是一旦 s 以 'bob' 開頭,它就找不到任何東西。 都。 返回 -1。 這是為什么?
beg = 0
count = 0
s = "boboxboobt"
while beg >=0 :
beg = s.find('bob', beg)
print("beg is :", beg)
if beg > 0:
count +=1
beg +=2
print('Count is:', count)
print("beg is :", beg)
else:
print('negativ')
break
print('count ', count)
不,它不返回-1
,它返回零,這是完全有效的,所以第一個條件應該是:
if beg >= 0:
"boboxboobt".find('bob', 0)
返回0
,而不是-1
:
>>> s = "boboxboobt"
>>> s.find('bob', 0)
0
您的代碼中有一個逐一錯誤:
if beg > 0:
這不包括beg = 0
情況。 把它變成:
if beg > -1:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.