如何在 python 中為有 4 個或 5 個字母的國家生成帶有正則運算式的串列?
names = ['Azerbaijan', 'Zimbabwe', 'Cuba', 'Cambodia', 'Somalia','Mali', 'Belarus', "C?te d'Ivoire", 'Venezuela', 'Syria', 'Kazakhstan', 'Austria', 'Malawi', 'Romania', 'Congo (Brazzaville)']
我試圖這樣做,但它回傳一個空串列:
import re
n = [w for w in names if re.findall(r'[A-Z]{4,6},', str(names))]
print(n)
Output:
[]
這是一個練習,這就是為什么我只能使用模塊 re。任何幫助將不勝感激。
uj5u.com熱心網友回復:
您可以使用len(w).
>>> names = ['Azerbaijan', 'Zimbabwe', 'Cuba', 'Cambodia', 'Somalia','Mali', 'Belarus', "C?te d'Ivoire", 'Venezuela', 'Syria', 'Kazakhstan', 'Austria', 'Malawi', 'Romania', 'Congo (Brazzaville)']
>>> [w for w in names if w.isalpha() and (len(w) in range(4,6))]
['Cuba', 'Mali', 'Syria']
但是如果你想解決它,regex你可以使用re.search如果你有的話numbers,list你可以使用walrusoperator ( :=) for python >= 3.8
names = ['1234', 'Azerbaijan', 'Cuba']
print([w for w in names if (tmp := re.search(r'[A-Za-z]{4,5}', w)) and (tmp.group(0) == w)])
# ['Cuba']
對于 python < 3.8,您可以使用try/except.
names = ['1234', 'Azerbaijan', 'Cuba']
res = []
for w in names:
try :
if re.search(r'[A-Za-z]{4,5}', w).group(0) == w:
res.append(w)
except AttributeError:
continue
print(res)
# ['Cuba']
uj5u.com熱心網友回復:
如果你需要使用 re 那么這里是你的答案find words of length 4 using regular expression
如果您不需要使用 re 只需執行 n = [name for name in names if len(name) in (4,5)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520250.html
標籤:Python细绳列表
