0

I want to get the float that sits between two different signs.

text="value_1 : 12.14% ,value_2 : 14.14% ,value_3 : 92.23% ,value_3 : 17.22% ,"

How can I grab only the number between the : and % chars?

1 Answer 1

2

very not pythonic way, also making many assumptions.

text = "value_1 : 12.14% ,value_2 : 14.14% ,value_3 : 92.23% ,value_3 : 17.22% ,"

s = text.split(',')
for part in s:
    if '%' in part:
        number = part.split(':')[1].strip()[:-1]
        print(number)

Here's the regex solution:

text = "value_1 : 12.14% ,value_2 : 14.14% ,value_3 : 92.23% ,value_3 : 17.22% ,"
regex = r'\:.*?(\d+\.\d+)%' # find all parts starting with the ';' char, 
                            # then skip all characters until digit is found, 
                            # and then extract the float number until the 
                            # '%' char appears
res = re.findall(regex, text)
for r in res:
    print(r)
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much, but may I ask what you meant by not a pythonic method ?is there another or better way to get the result I need?
@BaßelMutlak I mean that the first solution is quick and dirty one, and very specific. I prefer the regex.

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.