2016-08-28 39 views
3

我有一個函數,它需要一個計數和一個字符串作爲輸入。它應該返回該長度計數字符串中所有單詞的列表,以及更多。但是,Python不能識別我的變量並返回一個空列表。正則表達式re.findall()

def word_number(count, string): 
    return re.findall(r'\w{count,}', string) 

如何傳遞變量'count'以便函數返回count和更長的單詞?

回答

2

您可以使用str.format來實現您的目標。

def word_number(count, string): 
    return re.findall(r'\w{{{0},}}'.format(count), string) 
+0

需要加倍了最外面的大括號這個工作:'R '\ w {{{0}}}'' –

+0

哦謝謝, 你是對的。 –

5

您可以使用printf樣式格式:

re.findall(r'\w{%s,}' % count, string) 
+0

非常感謝,那真讓我失望! – fortune