Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Number before a Character in a String Using Python

I'm trying to extract the number before character "M" in a series of strings. The strings may look like:

"107S33M15H"
"33M100S"
"12M100H33M"

so basically there would be a sets of numbers separated by different characters, and "M" may show up more than once. For the example here, I would like my code to return:

33
33
12,33 #doesn't matter what deliminator to use here

One way I could think of is to split the string by "M", and find items that are pure numbers, but I suspect there are better ways to do it. Thanks a lot for the help.

like image 562
Helene Avatar asked Mar 22 '16 23:03

Helene


People also ask

How do you extract numbers from a string in Python?

This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.

How do I extract a specific part of a string in Python?

Getting a substring of a string is extracting a part of a string from a string object. It is also called a Slicing operation. You can get substring of a string in python using the str[0:n] option.


1 Answers

You may use a simple (\d+)M regex (1+ digit(s) followed with M where the digits are captured into a capture group) with re.findall.

See IDEONE demo:

import re
s = "107S33M15H\n33M100S\n12M100H33M"
print(re.findall(r"(\d+)M", s))

And here is a regex demo

like image 125
Wiktor Stribiżew Avatar answered Sep 25 '22 20:09

Wiktor Stribiżew