假设我有一个字符串"aaatapoaaatacoaaa"
,我想查找"taco"
出现的次数,但如果字母"c"
替换为"tapo"
,我仍想添加总金额其他字符,因此"taoo"
或str.find
等字词仍然有效。如果没有像def count_taco(a):
amount = 0
for letter in a:
count_taco("aaatapoaaatacoaaa")
这样的内置字符串搜索方法,我该怎么做?
到目前为止我才得到:
mathavg
答案 0 :(得分:0)
这应该有效:
>>> def count_taco(a):
amount = 0
chars = 'abcdefghijklmnopqrstuvwxyz'
for c in chars:
s = 'ta{}o'.format(c)
if s in a:
amount += a.count(s)
return amount
>>> my_test = 'aaatapoaaatacotaooaaatacotapo'
>>> count_taco(my_test)
5 #tapo - taco - taoo - taco - tapo