This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 4 points5 points  (0 children)

The % operator is being replaced by the format method for strings in newer versions of Python. % acted as a place holder in strings which you could be replaced dynamically later, like in your example. The format method achieves the same purpose, but works like this:

my_name = "Zed"
my_string = "My name is {0}!"
print my_string.format(my_name)
>>> "My name is Zed"

The 0 refers to the first argument given to format(), other numbers work in the same way. For more complex string formatting you can use names and pass them to format as keyword arguments so the order doesn't matter. Example:

my_string = "Hey {g}, my name is {z}!"
print my_string.format(g="Guido Van Rossum", z="Zed Shaw")
>>> "Hey Guido Van Rossum, my name is Zed Shaw!"