It's a string formatting syntax (it's borrowed from C.
Python supports formatting values as strings. While this can include very complex expressions, the most basic usage is to insert a value into a string in the %s placeholder.
Example 1:
#!/usr/bin/env python # -*- coding: utf-8 -*- name = "Tom" print "Hello %s" % name
result:
Hello Tom
Example 2:
#!/usr/bin/env python # -*- coding: utf-8 -*- name = raw_input("who are you?") print "hello %s" % (name,)
result:
who are you?dengao hello dengao
NOTE: The %s token allows me to insert (and potentially format) strings. Note that the %s token is replaced with whatever is passed to the string after the % sign. Also note that I'm also using a tuple here (optional when you only have one string using a tuple) to illustrate that multiple strings can be inserted and formatted in one statement.
Just to help you more, here's how you can use multiple formats in one string
"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".
If you use int instead of string, use %d instead of %s.
"My name is %s and i'm %d" % ('john', 12) #My name is john and i'm 12.
Summary: The % operator is used to format strings. Inside the string, %s means replace with a string, %d means replace with an integer, there are several % placeholders, followed by several variables or values, and the order should correspond well. If there is only one %, the parentheses can be omitted.
Common placeholders are:
placeholder replacement %d integer %f float %s string %x hex integer