Conversational Programming: How To Use The Percent Sign Operator in Python

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.

13 thoughts on “Conversational Programming: How To Use The Percent Sign Operator in Python

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

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

  3. 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!

  4. 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 //

  5. 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 😉

Leave a Reply

Your email address will not be published. Required fields are marked *