Difference Between %s and %d in Python String Formatting

Syed Moiz Haider Oct 10, 2023
Difference Between %s and %d in Python String Formatting

The tutorial explains the difference between %s and %d in Python string formatting. We will first describe the use of %s and %d separately and then compare the usage of both operators. The tutorial provides detailed examples with codes to clearly state the usage and difference between %s and %d in Python.

%d in Python String Formatting

The %d operator is used as a formatting string in Python. It is a placeholder for an integer. The value associated with %d is provided in a tuple using % or modulo operator. It is necessary to maintain the order of the values to be printed. However, if the Python version is 3, then the print statement will be given in parenthesis; otherwise, the print statement is not given in parenthesis.

An example code is given below to illustrate further how to use %d in Python.

age = 10
print("John Doe is %d years old" % age)

Output:

John Doe is 10 years old

However, in the case of floating-point numbers, the %d operator automatically converts them to decimal values. An example code is given below.

area = 24.6
print("The area of this plot is %d sq meter." % area)

Output:

The area of this plot is 24 sq meter.

%s in Python String Formatting

In Python, % is used with different data types for different purposes. %s is used as a placeholder for the string values. However, it is specifically used for the purpose of string concatenation. A string formatter can take any value and place it inside the string with automatic type conversion. It can be used to append multiple values to a string. An example code is given below to demystify the use of %s in Python.

name = "john doe"
print("The name of the applicant is %s." % name)

Output:

The name of the applicant is john doe.

Comparison Between %s and %d Operators in Python

A comparison between %s and %d operators in Python is given below.

%s %d
It is used as a placeholder for string values %d is used as a placeholder for integer values
It can accept any other data type as well If a string is specified for %d operator in Python, it will give an error
The string conversion is done using the str() method. The conversion is done before formatting The conversion in %d is done, before formatting, using the int() method.
Syed Moiz Haider avatar Syed Moiz Haider avatar

Syed Moiz is an experienced and versatile technical content creator. He is a computer scientist by profession. Having a sound grip on technical areas of programming languages, he is actively contributing to solving programming problems and training fledglings.

LinkedIn

Related Article - Python String