Reputation: 129
So I have looked at the post here: how to show Percentage in python and used the solution.
S = 'ftp'
"{0:.0f}%".format(S.count('f') / 9 * 100)
The desired output is 11%, but when I run the code using the format specified I get "0%" instead of the 11% that I want. Any push in the right direction would be much appreciated.
Upvotes: 0
Views: 4554
Reputation: 388313
If you want to show a percentage, you should just use the percent formatter directly:
>>> '{:.0%}'.format(S.count('f') / 9)
'11%'
As others already noted, Python 2 will use integer division if both arguments are integers, so you can just make the constant a float instead:
>>> '{:.0%}'.format(S.count('f') / 9.)
'11%'
Upvotes: 1
Reputation: 882606
It's because (in Python 2) you're using integer division where 3 / 9
gives you zero.
You can switch to floating point division:
"{0:.0f}%".format(S.count('f') / 9.0 * 100)
and you'll see why that works in the following transcript:
>>> 3/9
0
>>> 3/9.0
0.3333333333333333
Alternatively, you can rearrange your operations so that you multiply first:
"{0:.0f}%".format(S.count('f') * 100 / 9)
Upvotes: 0
Reputation: 143097
It works in Python 3 but for Python 2 you need atleast one float number to get float result for /
You can add . (dot) to 9 to have float number.
S = 'ftp'
"{0:.0f}%".format(S.count('f') / 9. * 100)
Upvotes: 0
Reputation: 5659
The problem is not in the format statement, just the arithmetic - your integer division makes S.count('f') / 9 return 0. Changing your 9 to 9.0 should work.
Upvotes: 1