What does %s mean in a Python format string?

What does %s mean in a Python format string?

It is a string formatting syntax (which it borrows from C).

Please see PyFormat:

Python supports formatting values into
strings. Although this can include
very complicated expressions, the most
basic usage is to insert values into a
string with the %s placeholder.

Here is a really simple example:

#Python 2
name = raw_input(who are you? )
print hello %s % (name,)

#Python 3+
name = input(who are you? )
print(hello %s % (name,))

The %s token allows me to insert (and potentially format) a string. Notice that the %s token is replaced by whatever I pass to the string after the % symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.

Andrews answer is good.

And just to help you out a bit more, heres how you use multiple formatting in one string:

Hello %s, my name is %s % (john, mike) # Hello john, my name is mike.

If you are using ints instead of string, use %d instead of %s.

My name is %s and Im %d % (john, 12) #My name is john and Im 12

What does %s mean in a Python format string?

The format method was introduced in Python 2.6. It is more capable and not much more difficult to use:

>>> Hello {}, my name is {}.format(john, mike)
Hello john, my name is mike.

>>> {1}, {0}.format(world, Hello)
Hello, world

>>> {greeting}, {}.format(world, greeting=Hello)
Hello, world

>>> %s % name
{s1: hello, s2: sibal}
>>> %s %name[s1]
hello

Leave a Reply

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