Why do we use %d in python?

These are all informative answers, but none are quite getting at the core of what the difference is between %s and %d.

%s tells the formatter to call the str() function on the argument and since we are coercing to a string by definition, %s is essentially just performing str(arg).

%d on the other hand, is calling int() on the argument before calling str(), like str(int(arg)), This will cause int coercion as well as str coercion.

For example, I can convert a hex value to decimal,

>>> '%d' % 0x15
'21'

or truncate a float.

>>> '%d' % 34.5
'34'

But the operation will raise an exception if the argument isn't a number.

>>> '%d' % 'thirteen'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

So if the intent is just to call str(arg), then %s is sufficient, but if you need extra formatting (like formatting float decimal places) or other coercion, then the other format symbols are needed.

With the f-string notation, when you leave the formatter out, the default is str.

>>> a = 1
>>> f'{a}'
'1'
>>> f'{a:d}'
'1'
>>> a = '1'
>>> f'{a:d}'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'

The same is true with string.format; the default is str.

>>> a = 1
>>> '{}'.format(a)
'1'
>>> '{!s}'.format(a)
'1'
>>> '{:d}'.format(a)
'1'

The following article will cover points like % operator, string formatting, and most importantly, focus on the %d usage in Python.

Do you have some experience with the C or Pearl language? If yes, you would have worked with the format specifier like %d, %s, %f, etc., in the printf function. Similar to C, Python too can mimic this ancient functionality, using the ‘ % ‘ operator. Also known as string formatting or string modulo or interpolation operator. As it interpolates various class types into a formatted string.

There are better alternatives to it, for instance, the format method and f-strings. However, string formatting is widely used and is still a part of python3. It is likely the % operator will get discontinued from the upcoming python versions. Hence you should prefer the f-strings or format method. With this in mind and for the sake of knowledge, we will discuss it. Read more here.

  • How to use %d in Python
    • Using %d for formatting strings in Python
    • Using %d in a loop
  • Alternatives
    • Formatting strings using f-strings
    • Formatting strings using the str.format method
  • Difference between %s and %d
    • %s
    • %d
  • Template strings instead of %d
  • FAQs
  • Conclusion
  • Trending Python Articles

How to use %d in Python

Why do we use %d in python?
Working of %s, %f, and %d in Python

%d acts as a placeholder for the digits. Similarly, %s and %f act like placeholders for the strings and the floating-point values. Let’s understand how we can use %d in Python with some examples.

Using %d for formatting strings in Python

a = 10
b = 11
c = a + b
print("%d + %d = %d" % (a,b,c))

Why do we use %d in python?
%d for displaying values

Using %d in a loop

num_range = int(input("Enter a number:"))

for i in range(num_range):
    print("%d" %(i**2),end=", ")

Why do we use %d in python?
%d in for loop

Alternatives

Better alternatives to string formatting are the format method and f-strings. Let’s look at how we can use them. For instance.

Formatting strings using f-strings

Example 1:

a = 10
b = 11
c = a + b

# using f-strings
print(f"{a} + {b} = {c}")

In the above code, we add two numbers, store the result in the third variable, and later print all the values together using the f-strings.

Why do we use %d in python?
Using an f-strings method for formatting strings

Example 2:

number, count = 5, 0

while count < number:
    print(f"Count: {count}")
    count += 1

The above example code prints the formatted string with an increasing value of count till the number.

Why do we use %d in python?
Using f-strings in a loop

Formatting strings using the str.format method

Example 1:

a = 10
b = 11
c = a + b

# usign format method
print("{0} + {1} = {2}".format(a, b, c))

In the above code, we add two numbers, store the result in the third variable, and later print all the values together using the format method of the str class. Here, 0, 1 & 2 represent values of a, b, c respectively.

Why do we use %d in python?
Using the format method for formatting strings

Example 2:

number, count = 0, 5

while count > number:
    print("Count: {}".format(count))
    count -= 1

The above example code prints the formatted string with decreasing value of count till the number.

Why do we use %d in python?
Using the str.format method in a loop

Difference between %s and %d

The %s is used for interpolating strings, while %d is used for integers. %s does string conversion before formatting. At the same time, %d does decimal conversion before formatting the strings.

Let’s take examples to clear our point.

%s

string1 = "You’re you, you see," 
string2 = " and nobody else. "
string3 = "You are you, right?"

print('%s%s%s' %(string1,string2,string3))

Why do we use %d in python?
Using %s

Recommended Reading | Demystifying the Secrets of Python %s

%d

birthyear = int(input("Enter birth year:"))
print("You're %d years old." %(2022-birthyear))

Why do we use %d in python?
Using %d

Template strings instead of %d

Python has another tool in its belt named template strings which is less powerful than its counterparts.

from string import Template

temp = Template('Hello, $name!')
print(temp.substitute(name = 'Kisuke'))

Why do we use %d in python?
Using template strings instead of %d

FAQs

What do %d, %s, and %f mean in Python?

%d acts as a placeholder for the digits. Similarly, %s and %f act like placeholders for the strings and the floating-point values.

How do I print %d output in Python?

You can use string formatting in Python. For instance:
print("Income :$%d" %(10000))
Output: Income: $10000

Can we use %d in regex?

Regex used ‘ \d ‘ for matching values from 0-9. It serves an entirely different purpose compared to string formatting’s %d.

Conclusion

% operator in Python is a relic of the past, in other words. There are better alternatives. For instance, f-strings and format methods are more readable and more pythonic. However, the % operator played a vital role once.

  • Why do we use %d in python?

    ImportError: Attempted Relative Import With No Known Parent Package

    September 24, 2022

  • Why do we use %d in python?

    Easily Convert Unix time to Datetime in Python

    by Vishnu VenkateshSeptember 13, 2022

  • Why do we use %d in python?

    How To Convert PIL Images to Numpy Array

    by Vishnu VenkateshSeptember 10, 2022

  • Why do we use %d in python?

    The A-Z of Python Virtualenv Location

    by Vishnu VenkateshSeptember 8, 2022

What does %d and %s do in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

What is %d and %i in Python?

Here's what python.org has to say about %i: Signed integer decimal. And %d: Signed integer decimal. %d stands for decimal and %i for integer. but both are same, you can use both.

Why %F is used in Python?

Python f-string is the newest Python syntax to do string formatting. It is available since Python 3.6. Python f-strings provide a faster, more readable, more concise, and less error prone way of formatting strings in Python.

What is %R and %S in Python?

The %s specifier converts the object using str(), and %r converts it using repr().

Tải thêm tài liệu liên quan đến bài viết Why do we use %d in python?