%s in Python?

In this article, we would explore the topic – %s in Python. %s is mainly used to insert a value inside a string. Here, s means that we are using string values.

The string value can be in form of a single value, tuple or even a dictionary. As of now, it may look a bit confusing. But, things will get clear when we illustrate it with examples.

Example I. Through a simple Hello World! program.

x = "World!"
print("Hello, %s" %x)

It will return with –

Hello, World!

Example II. Using tuples as string values.

x = ("World!", "are")
print("Hello, %s How %s you?" %x)

This would return with –

Hello, World! How are you?

In this example, we have used x as tuple. The two elements i.e. “World!” and “are” are there in tuple x. These elements are later used with the print() method in the same order. But, we can decide where we want to tuple elements to be placed in a string through %s.

Example III. We can achieve the above results in Example II through multiple %s as well. Although, we don’t consider it as efficient when compared with using a tuple. But, still you may require it in certain conditions. For separate values, we using two different variable x1 and x2.

x1 = "World!"
x2= "are"
print("Hello, %s How %s you?" %(x1, x2))

It would return with –

Hello, World! How are you?

In conclusion, we saw how %s in Python is used to insert a value inside the string. Furthermore, we also explained it using three examples. One of which was insert values through a tuple.

Similar Posts