The tutorial explains the difference between
%d in Python string formatting. We will first describe the use of
%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
%d in Python.
%d in Python String Formatting
%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)
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)
The area of this plot is 24 sq meter.
%s in Python String Formatting
% 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)
The name of the applicant is john doe.
%d Operators in Python
A comparison between
%d operators in Python is given below.
|It is used as a placeholder for string 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
||The conversion in %d is done, before formatting, using the