Python %d For Formatting Integer Inside 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 complimentary for the %d specifier.

%d Format Specifier

The %d can be used with different methods like print(), format(), etc. Generally used inside the string and the integer values are provided with different parameters. Take a look at the following syntax where the numbers will be printed with the %d format specifier inside a string without the need to convert an integer into the string format.

age = 35

("My age is %d" , age)

Print Integers Inside String with %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) )

With multiple integers you can provide multiple item tuple like below.

age = 40

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

Leave a Comment