Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Extract a decimal number before a specific substring

I want to extract a number before a specific substring ("per cent")

I tried to used the split function

str1="The percentage of success for Team A is around 7.5 per cent. What about their season ?"
print(str1.split("per cent",1)[0])

Expected result: "7.5"

Actual result: "The percentage of success for Team A is around 7.5"

like image 341
aelayath Avatar asked Jul 04 '19 08:07

aelayath


2 Answers

You could use str.index to find the index where per cent takes place, slice the string up to the resulting index, then rstrip and split keeping the last element from the resulting list:

str1[:str1.index('per cent')].rstrip().split()[-1]
# '7.5'
like image 61
yatu Avatar answered Oct 26 '22 14:10

yatu


You can use regex for this:

import re

str1="The percentage of success for Team A is around 7.5 per cent. What about their season ?"

m = re.search('([0-9.-]+) per cent', str1)
m[1]
=>7.5

What I did is the following: I created a regex that matches any combination of digits, dash and dot (to crudely match a number that is possibly negative) followed by the exact text per cent.

I specified the number as a group and so you can get it by accessing the 1-th index of the found match.

like image 3
Ivaylo Strandjev Avatar answered Oct 26 '22 14:10

Ivaylo Strandjev