Jump to content

What does % command mean in Python?

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Morik

Morik

    Newbie

  • Members
  • Pip
  • 1 posts
I am trying to understand this section of a python tutorial

Exercise 6: Strings And Text — Learn Python The Hard Way, 2nd Edition

I don't understand how the %s or %d or %r work. Do they assign the value to s, d, or r appropriately? I looked in the python documentation and there does not seem to be anything. Wouldn't it just be easier to declare r = 10?

#2
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 890 posts
  • Location:::1
Those are used for easier string manipulation. %s is replaced with string, %d with integer and so on. They allow you to form strings easier.
A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#3
TkTech

TkTech

    The Crazy One

  • Moderators
  • 1,396 posts
I'm a bit late to the party, but an interesting beginner question none the less.
First up, a bit of advice. One of Python's strongest points is the excellent documentation available to you, although it can sometimes be a bit tricky to find. The documentation is right here for string formatting.
Reading the documentation should help you figure out what's going on, butit doesn't answer why.

In python, strings are immutable, instead of mutable. This means that once you make a string it cannot be changed again without creating a new string. Lets write an example which will print a string 1000 times two different ways:
for i in range(0, 1000):
    print "Working on #%d, out of %d" % (i, 1000)
...and...
for i in range(0, 1000):
    print "Working on #" + str(i) + " out of " + str(1000)

Both of these produce identical output, but the first example will perform better than the second. Why? Well, the first version only produces a single string ("Working on #%d, out of %d") and the print method will replace %d and other format specifiers as it comes across them. The second example actually produces six different strings before printing. This is what happens when is equal to 1.
  • "1" - str(i)
  • "1000" - str(1000)
  • "Working on #"
  • "Working on #1" - "Working on #" + str(i)
  • "Working on #1 out of " - "Working on #" + str(i) + " out of "
  • "Working on #1 out of 1000" - "Working on #" + str(i) + " out of " + str(1000)"
  • print
It's always recommended that you use string formatting whenever you can, especially if the string is going to be modified many times (such as in a loop). It should be noted that this doesn't always offer an advantage as certain version of python handle it differently, but it doesn't perform worse​ in either case.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users