[英]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.