Reputation: 362
I'd like to format a number as percentage, i.e. 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.
Upvotes: 2
Views: 3324
Reputation: 7224
You can use f'' strings:
num = .331
print(f'the percent is {num*100:6.2f} %')
percent is 33.10 %
https://realpython.com/python-f-strings/
Upvotes: 1
Reputation: 368
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 %
Upvotes: 2
Reputation: 51
Have you checked how to use f-strings?
number_1 = 0.331
string_1 = f'{number_1 * 100} %'
print(string_1)
output: 33.1 %
Upvotes: 0