How can I generate a list with regex in python for countries with 4 or 5 letters?
JavaScript
x
2
1
names = ['Azerbaijan', 'Zimbabwe', 'Cuba', 'Cambodia', 'Somalia','Mali', 'Belarus', "Côte d'Ivoire", 'Venezuela', 'Syria', 'Kazakhstan', 'Austria', 'Malawi', 'Romania', 'Congo (Brazzaville)']
2
I was trying to do this but it returns an empty list:
JavaScript
1
9
1
import re
2
3
n = [w for w in names if re.findall(r'[A-Z]{4,6},', str(names))]
4
5
print(n)
6
7
Output:
8
[]
9
It is an exercise that’s why I can only do it with the module re. Any help will be appreciate.
Advertisement
Answer
You can use len(w)
.
JavaScript
1
5
1
>>> names = ['Azerbaijan', 'Zimbabwe', 'Cuba', 'Cambodia', 'Somalia','Mali', 'Belarus', "Côte d'Ivoire", 'Venezuela', 'Syria', 'Kazakhstan', 'Austria', 'Malawi', 'Romania', 'Congo (Brazzaville)']
2
3
>>> [w for w in names if w.isalpha() and (len(w) in range(4,6))]
4
['Cuba', 'Mali', 'Syria']
5
But if you want to solve it with regex
you can use re.search
and
If maybe you have numbers
in list
you can use walrus
operator (:=
) for python >= 3.8
JavaScript
1
4
1
names = ['1234', 'Azerbaijan', 'Cuba']
2
print([w for w in names if (tmp := re.search(r'[A-Za-z]{4,5}', w)) and (tmp.group(0) == w)])
3
# ['Cuba']
4
For python < 3.8 you can use try/except
.
JavaScript
1
12
12
1
names = ['1234', 'Azerbaijan', 'Cuba']
2
3
res = []
4
for w in names:
5
try :
6
if re.search(r'[A-Za-z]{4,5}', w).group(0) == w:
7
res.append(w)
8
except AttributeError:
9
continue
10
print(res)
11
# ['Cuba']
12