简体   繁体   中英

Formatting in python with locale

I am trying to format a set of a set of numbers to show as as xxx,xxx,xxx instead of xxxxxxxxxxxxxxxx.xxxxxxxxxxxxxx

The formatter iterates over a dictionary, where the values are a list.

This is what it looks like:

{'ST': [Decimal('21529992.247811'), 
Decimal('75922363.959394'), Decimal('1.688401841437798245794341100')], 
'LQT': [Decimal('23034058.811000'), Decimal('45706418.420000'), 
Decimal('0.243186493430996726476558100')], 'SR': 
[Decimal('8389288.802664'), Decimal('0393135.373964'), 
Decimal('-2.146515189191049793306943120')], 'MIS7': 
[Decimal('6382868.080000'), Decimal('5336228.320000'), 
Decimal('-4.879627090905261579809913330')], 'LQ': 
[Decimal('98508613.709000'), Decimal('38822011.125000'), 
Decimal('-3.983067033313078110002846960')] }

This is the incorrect coding that I have:

    import locale
    locale.setlocale(locale.LC_ALL, '')
    for k in result.keys():
        if result[k] == result[k]:
            result[k] = locale.format('%d', result[k], grouping = True)
    if len(result) == 0:
        result["None"] = "None" 

My error string is long, but this looks like the main bit:

TypeError: %d format: a number is required, not list

What do I need to do? Thank you

Why not simply:

    import locale
    locale.setlocale(locale.LC_ALL, '')
    for r in result:
        for k in result[r]:
            print locale.format('%2f', k, grouping = True) # Note there is not result[k]. Use your preferred number format instead of '%2f'

and here is the output using '%2f' :

23.034.058,811000
45.706.418,420000
0,243186
8.389.288,802664
393.135,373964
-2,146515
6.382.868,080000
5.336.228,320000
-4,879627
98.508.613,709000
38.822.011,125000
-3,983067
21.529.992,247811
75.922.363,959394
1,688402

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