Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I write responsive regular expression in Python?

I want to get up to the first digit other than 0 after the dot.
If there is a number other than 0 after the dot, it should be taken as 2 digits. So it must be sensitive.How do I do this with regular expressions or Python math library?
Here are examples

"0.00820289933" => "0.008"
"0.00000025252" => "0.0000002"
"0.858282815215" => "0.85"
"0.075787842545" => "0.07"
def format_adjusted_value(value):
    str_value = str(value)

    if '.' in str_value:
        match = re.match(r'(\d*\.\d*?[1-9])0*$', str_value)

        if match:
            formatted_value = match.group(1)
        else:
            match = re.match(r'(\d*\.\d*?[0-9])0*$', str_value)
            formatted_value = match.group(1) if match else str_value
    else:
        formatted_value = str_value

    return formatted_value

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Try like this

import re

def format_adjusted_value(value):
    str_value = str(value)

    match = re.match(r'\d*\.\d*?[1-9]', str_value)
    formatted_value = match.group(0) if match else str_value

    return formatted_value

test_values = [
    "0.00820289933",
    "0.00000025252",
    "0.858282815215",
    "0.075787842545",
]

for value in test_values:
    print(f"{value} => {format_adjusted_value(value)}")

Output:

0.00820289933 => 0.008
0.00000025252 => 0.0000002
0.858282815215 => 0.8
0.075787842545 => 0.07
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading