0

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.