PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 18, 2022

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

 September 18, 2022     percentage, printing, python, python-2.x     No comments   

Issue

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

Solution

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%


Answered By - El Bert
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,215,794

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing