[英]int doesn't work in def within regular expression in python
我需要編寫一個函數,該函數需要一個計數和一個字符串,並返回該字符串中所有字的字符長度或更長的列表。
我的職能是:
import re
def find_words(count, a_str):
count = int(count)
return re.findall(r'\w{},'.format(int(count)), a_str)
但這不起作用,它返回空列表:
例:
find_words(4, "dog, cat, baby, balloon, me")
應該返回:
['baby', 'balloon']
正則表達式不正確。 {}
被解釋為format
占位符,但您希望它是正則表達式的{}
,用於指定重復次數。 您需要在此處使用r'\\w{{{}}}'
。 觀察差異:
>>> r'\w{},'.format(4)
'\\w4,'
>>> r'\w{{{},}}'.format(4)
'\\w{4,}'
然后它可以正常工作:
import re
def find_words(count, a_str):
count = int(count)
return re.findall(r'\w{{{},}}'.format(count), a_str)
>>> find_words(4, "dog, cat, baby, balloon, me")
['baby', 'balloon']
為什么選擇RegExp?
>>> string = "dog, cat, baby, balloon, me"
>>> [word for word in string.split(', ') if len(word) >= 4]
['baby', 'balloon']
因此功能可能如下所示:
>>> def find_words(count, a_str):
... return [word for word in a_str.split(', ') if len(word) >= count]
...
>>> find_words(4, 'dog, cat, baby, balloon, me')
['baby', 'balloon']
您可以嘗試以下方法:
def find_words(count, a_str):
s = [re.findall("\w{"+str(count)+",}", i) for i in ["dog, cat, baby, balloon, me"]]
return s[0]
print(find_words(4, ["dog, cat, baby, balloon, me"]))
輸出:
['baby', 'balloon']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.