2

So I try to print only the month, and when I use :

regex = r'([a-z]+) \d+'
re.findall(regex, 'june 15')

And it prints : june But when I try to do the same for a list like this :

regex = re.compile(r'([a-z]+) \d+')
l = ['june 15', 'march 10', 'july 4']
filter(regex.findall, l)

it prints the same list like they didn't take in count the fact that I don't want the number.

2
  • filter keeps the whole thing if bool(condition)=True all items in your list match and are thus kept Commented Dec 10, 2018 at 0:10
  • if each element is only one date use [re.sub(regex,'\\1',x) for x in l] Commented Dec 10, 2018 at 0:18

1 Answer 1

5

Use map instead of filter like this example:

import re

a = ['june 15', 'march 10', 'july 4']
regex = re.compile(r'([a-z]+) \d+')
# Or with a list comprehension
# output = [regex.findall(k) for k in a]
output = list(map(lambda x: regex.findall(x), a))
print(output)

Output:

[['june'], ['march'], ['july']]

Bonus:

In order to flatten the list of lists you can do:

output = [elm for k in a for elm in regex.findall(k)]
# Or:
# output = list(elm for k in map(lambda x: regex.findall(x), a) for elm in k)

print(output)

Output:

['june', 'march', 'july']
Sign up to request clarification or add additional context in comments.

2 Comments

Or just a list comprehension: output = [regex.findall(x) for x in a]
Great !! But now I have all the month in a list inside a list. How can I deal with it and put them in a simple list instead ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.