Python %d and %s For Formatting Integer and String

Python is developed with the C programming language and some of the language syntaxes are borrowed from the C. The % is an operator used to format a given string in different ways. The %d is the format specifier used to print integers or numbers. There is also the %s string specifier which is used to print and format string values and string variables.

%d Format Specifier

One of the popular use cases for the %d format specifier is using the print() method. In the following example, we will the age which is an integer inside a string by using the %d format specifier. The %d format specifier can be also used multiple times. We will provide the integers as a tuple in the following example.

age = 40

print("My age is %d" % (age) )
My age is 40

With multiple integers, you can provide multiple item tuples like below.

age = 40

print("My age is %d. I have born in %d." % ( age , 1980 ) )

%s Format Specifier

The %s can be used with different methods like print(), format(), etc. In general %s is used to put and print string values or string variables. In the following example, we want to print the name variable in a parameterized way.

name = "Ahmet"

print("My name is %s" % name)
My name is Ahmet

Alternatively, we can use the %s multiple times for a single string or print().

name = "Ahmet"

surname = "Baydan"

print("My name is %s %s" % (name,surname))
My name is Ahmet Baydan

%d and %s Format Specifiers At The Same Time

The %d and %s format specifiers can be also used at the same time. Just provides the integer and string values or variables as a tuple. In the following example, we provide the name and age as a string and integer values.

name = "Ahmet"

age = 8

print("My name is %s and I am %d years old." % (name,age))
My name is Ahmet and I am 8 years old.

Leave a Comment