Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print a '%' sign using string formatting?

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 
like image 783
Eric1989 Avatar asked Feb 05 '15 12:02

Eric1989


People also ask

How do you put a percent sign in a string?

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.

How do you use %s on a string?

%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.

How do you print a string symbol in Python?

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') .

How do you use %d in strings?

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.


1 Answers

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% 
like image 122
El Bert Avatar answered Oct 13 '22 12:10

El Bert