2015-05-15 39 views
0

我的任務是用正則表達式創建一個函數,該函數返回長度爲012或更長的單詞字符countPython:使用必須位於大括號內的變量格式化字符串{}

這裏是我的嘗試:

import re 

# EXAMPLE: 
# >>> find_words(4, "dog, cat, baby, balloon, me") 
# ['baby', 'balloon'] 

def find_words(count, a_string): 
    pattern = r'\w{{{},}}'.format(count) 
    return re.findall(pattern, a_string) 

之所以花括號的困境的是,我試圖escape them

,我想會是這樣的\w{count,}

編輯最終的搜索字符串(pattern):忘記了return聲明在原來的職位。我會在這裏留下這個,因爲進來的答案實際上很有價值。

+2

'return re.findall(pattern,a_string)'。注意是重要的:) –

+0

哎呀...我現在要睡覺 – Travis

+0

用途:''「{{{0:s}}}」。format(「4」)''例如。 –

回答

3

爲什麼不使用%運算符?

In [1]: def find_words(count, a_string): 
    ...:  pattern = r'\w{%s,}' % count 
    ...:  return re.findall(pattern, a_string) 

In [2]: find_words(4, "dog, cat, baby, balloon, me") 
Out[2]: ['baby', 'balloon'] 
相關問題