I've made a little script to calculator percent; however, I wish to actually include the %
within the message printed...
Tried this at the start - didn't work...
oFile.write("Percentage: %s%"\n" % percent)
I then tried "Percentage: %s"%"\n" % percent"
which didn't work.
I'd like the output to be:
Percentage: x%
I keep getting
TypeError: not all arguments converted during string formatting
You can do this by using %% in the printf statement. For example, you can write printf(“10%%”) to have the output appear as 10% on the screen.
%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string.
To print any character in the Python interpreter, use a \u to denote a unicode character and then follow with the character code. For instance, the code for β is 03B2, so to print β the command is print('\u03B2') .
The %d operator is used as a placeholder to specify integer values, decimals or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values.
To print the %
sign you need to 'escape' it with another %
sign:
percent = 12 print "Percentage: %s %%\n" % percent # Note the double % sign >>> Percentage: 12 %
EDIT
Nowadays in python3 a better (and more readable) approach is to use f-strings. Note that other solutions (shown below) do work as well:
$python3 >>> percent = 12 >>> print(f'Percentage: {percent}%') # f-string Percentage: 12% >>> print('Percentage: {0}%'.format(percent)) # str format method Percentage: 12% >>> print('Percentage: %s%%' % percent) # older format, we 'escape' the '%' character Percentage: 12%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With