Reputation: 13
From this list problems= ["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]
I want to get these numbers "\d*\s"
that means 32,3801,45,123
Is there a way to look in each item of list and search there with a list comprehension ?
I have only this attempt print([x for x in problems if re.search(r'\d*\s',x)])
, but it prints whole item if the "\d*\s"
is there, so I get again ["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]
(My aim is have a lenght of the longer number of each item, that would be 3,4,2,3)
Upvotes: 0
Views: 43
Reputation: 987
You need to extract the first part before space in your strings. This can be done using group capturing. Here is the code you can use:
[re.search('(\d+)\s', x).group(1) for x in problems if re.search(r'(\d)*\s',x)]
Here (\d+)\s
matches for one or more digits before a whitespace character and we extract the first group using the group(1)
method.
Upvotes: 1