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"
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With