int在python

时间:2017-08-26 12:39:06

标签: python regex string string-formatting

我需要编写一个带有计数和字符串的函数,并返回字符串中所有单词字符长或长的单词列表。

我的功能是:

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']

3 个答案:

答案 0 :(得分:3)

正则表达式不正确。 {}被解释为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']

答案 1 :(得分:2)

为何选择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']

答案 2 :(得分:0)

你可以试试这个:

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']