The Percent Sign (%) is a interesting beast in the Python language. It does something called string formatting and it’s a mathematic operator as well. Whatever math is. Let’s find out what the POWER of the % is… first, we’ll learn by finding out what NOT to do.
print % ^ SyntaxError: invalid syntax
Easy fail. What’s next?
print "foo" % "bar" TypeError: not all arguments converted during string formatting
Formatting? I barely knew her! Ok, how about using this thing for real.
If I wrap the following text in PRE tags, WordPress munges the entire post. Yum!
print “whiskey%” % “tango”
ValueError: incomplete format
I’ve got more ways the percent operator can fail. Feel free to post others in the comments section.
TypeError: float argument required, not str TypeError: %d format: a number is required, not str ValueError: unsupported format character 'X' (0xXX) at index X
Why doesn’t this damn percent thing WORK?!!?!? Truth is, there’s a million ways to use the % operator incorrectly. To make it worse, exactly none of these errors were super helpful readable english, unless they got you here.
So here’s how you use it:
Modulus operation: Performs division like the typical forward slash (/) operator, but instead of returning the result, it returns the “remainder”:
16 % 4 0
or
16 % 5 1
Awesome! Lesson learned? Good, because you will never use modulus. Feel free to forget everything I’ve said above. Do not forget anything that follows.
String Formatting:
print "Holy Shit" Holy Shit
Ok, that didn’t have a percent sign in it. Just keeping you interested.
StringyStringerton = "Beets." print "Fact: Bears. %s Battlestar Galactica" % StringyStringerton Fact: Bears. Beets. Battlestar Galactica
The percent sign living inside the string says, “Wait up. I’ve got something interesting to tell you about.”
The very first character after the percent sign says what type of thing you want to say.
Please read the last paragraph again until you truly understand it.
Moving on. d is a Digit. f is a Float. s is a String. There are others, but I’ll go over these first.
How about this:
Bitches = 99 print "I have %d problems." % Bitches I have 99 problems.
Change it up. you don’t need to set the variable first!
print "I like %f numbers" % 100 I like 100.000000 numbers
What if I want to put leading zeros or padding before or after my numbers? Padding is easy. Put a <SPACE> before the percent sign, and a number after it. Like this:
print "I like %10s spacing" % "nice" I like nice spacing
Leading zeros is easy. Put a zero after the percent sign, followed by a number.
print "I love %05d woman." % 1 I love 00001 woman.
I can’t keep your attention forever, so I’ll make this brief. You can use unlimited string formatting operators (%), just separate them with a coma.
print "I love %s, but hate %s." % ("Honey Nut Cherios","milk") I love Honey Nut Cherios, but hate milk.
Templates is a better way to customize HUGE swaths of text… like a mail merge, if you’ve ever used it. I actually haven’t. Pity me.
There is official documentation about the infamous string formatting operator over at Python Docs. It’ll give you a good list of things to use after the percent sign to format things and wrap your head around a pole. I’m pretty darn sure that I broke WordPress with this post. So I’ll…
Yep! I need something better for writing about code.
18 replies on “Conversational Programming: How To Use The Percent Sign Operator in Python”
Nice, I used to read your fskin blog, but I’m starting to learn programming, nice blog.
“Thanks for the post, but ill stick to waiting for your next %b blog entry :P” % (‘fsckin’)
Thanks. I worked all of them. It was helpful practice.
I was having problems understanding the percent sign in certain code. It would look totally arbitrary or Greek to me. This really has helped me! Thanks so much.
Hey this was super helpful but FYI, some of your readers are women so feel free to use some other entertaining gender-specific examples like:
it = “RESPECT”
print “Find out what %s means to me.” %it
Find out what RESPECT means to me.
nothing like a bit of humour to make the point stick. thanks!
It’s like magic.
I can begin to understand it’s power. I am interested in more powers.
Here’s another extended example using multiple %d in one line:
for x in xrange(1, 11):
for y in xrange(1, 11):
print ‘%d * %d = %d’ % (x, y, x*y)
Source: https://wiki.python.org/moin/ForLoop
Looking at python for a school project, and this helped a lot. Thanks bro 🙂
Just found out that you’ve stopped working on this website. That’s a damn shame. Good luck on whatever project you’re working on now, then. This has still been a huge help. Thanks a lot!
Stumbled across this while searching for %f syntax. You can do rounding with it right away! Plus the spacing thing:
‘poops: %f’ % 12.3
// Result: poops: 12.300000 //
‘poops: %.1f’ % 12.3
// Result: poops: 12.3 //
‘poops: %10.1f’ % 12.3
// Result: poops: 12.3 //
You got a beautiful way of keeping my attention 😀
thank you so much now I can get back to learning python without
feeling headache when the % comes again 😉
Great post! Have nice day ! 🙂 zyusl
I always was interested in this subject and still am,
thanks forr posting.
huge props, big thank you
Wow, this was awesome. Keep writing this kind of posts, you will get a lot of people to this page if you continue doing this.
print (%)
print (“%”)
print %
print(‘%’)