简体   繁体   中英

Python format string for percentage with space before %

I'd like to format a number as percentage, ie 0.331 -> '33.1 %' .

The obvious way in simple code is to use '{:.1f} %'.format(percentage*100) Since I am only passing the format string to a function as in fn(dataframe, format='{:.1f}') , I cannot easily multiply the data with 100 (since data is used for calculations inside the function as well). Now Python has the % format specifier which almost does what I want: '{:.1%}'.format(0.331) gives '33.1%' , but I want '33.1 %' (as required by DIN 5008)

Is there a way to use insert the space between the number and percent symbol using the format string? So basically like '{:6.1%}'.format(0.331) but with the space on the other side of the number.

If that's not possible, I have to crack open the function the format string is passed to. And that seems a hacky solution that I'd like to avoid.

To be honest as a lazy programmer myself I would just use str.replace ( https://docs.python.org/3/library/stdtypes.html#str.replace ) after the formatting appended like this:

a = '{:.1%}'.format(0.331).replace('%', ' %')
print(a)

gives: 33.1 %

You can use f'' strings:

num = .331 
print(f'the percent is {num*100:6.2f} %')

the percent is   0.33 %

https://realpython.com/python-f-strings/

Have you checked how to use f-strings?

number_1 = 0.331

string_1 = f'{number_1 * 100} %'

print(string_1)

output: 33.1 %

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