简体   繁体   中英

remove last 0 decimals from string

I am working on comparing two text files, however I am stuck on one of the files adding ",00" at the end of each number, while the other file doesn't have ",00" if there are no decimals. I have fixed this by doing .replace(",00", "") However, when the digit is for example 30056,50 it does not remove that last 0.

I will give you an example I have these lines:

2770, -32847,39, 2338,69, -30508,70
1030, 136920, 0, 136920,00

I want the current output:

2770, -32847,39, 2338,69, -30508,7
1030, 136920, 0, 136920

How do I go about also removing the last 0 in decimals where the decimal is for example ,50 ?

Reproductibe example: A example.txt with this in it:

2770, -32847,39, 2338,69, -30508,70
1030, 136920, 0, 136920,00

a outout.py with this in it:

with open('example.txt', 'r') as f:
    lines = f.readlines()

    output = []

    for line in lines:
        temp = line.split(";")
        output.append(temp[0].replace(",00", ""))
        output.append(temp[2].replace(",00", ""))
        output.append(temp[3].replace(",00", ""))
        output.append(temp[4].replace(",00", ""))

    with open('result.txt', 'w') as outFile:
        outFile.write(', '.join(output))

This will create a result.txt which has this in it:

2770, -32847,39, 2338,69, -30508,70
1030, 136920, 0, 136920

Correctly removing the ",00". However, I also want it to remove the last 0 decimal in ,70 so that the output file will contain this:

2770, -32847,39, 2338,69, -30508,7
1030, 136920, 0, 136920

Use re.sub twice, first to remove 00 after the comma, and then to remove the terminal 0 after the comma:

import re
lst = ['10,00', '-30,70', '20,09', '0', '10', '100']
stripped_lst = [re.sub(r'(,\d)0', '\\1', re.sub(r',00', '', x)) for x in lst]
print(stripped_lst)
# ['10', '-30,7', '20,09', '0', '10', '100']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM