在任何地方字符串「代碼」的次數返回的字符串
"code"
隨時隨地出現在 給定的字符串,除了我們會接受任何字母爲'd'
的次數,所以"cope"
和"cooe"
計數。返回出現的給定的字符串import re def count_code(str): exp = '^co[a-z|A-Z]e$' count = 0 for i in range(len(str) - 1): if re.match(exp, str[i:i + 4]): count = count + 1 return count print count_code('aaacodebbb') # prints 1 print count_code('codexxcode') # prints 2 print count_code('cozexxcope') # prints 2
是否有實現這一目標,而無需使用正則表達式的任何其他方式:
我已經使用正則表達式下面的代碼實現這一點?
您的正則表達式變量效率低下。查看[re.findall](https://docs.python.org/2/library/re.html?highlight=re.findall#re.findall),並將其與[len](https:/ /docs.python.org/2/library/functions.html?highlight=len#len)。 – Phillip
*「有沒有其他方式......」 - 是的,當然有。你有真正的問題嗎? – jonrsharpe
@Phillip,謝謝,也會試試。 –