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 stringformattingorstring modulo or interpolationoperator. 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.
Contents
How to use %d in Python
![Demystifying the Secrets of Python %d (1) Demystifying the Secrets of Python %d (1)](https://i0.wp.com/www.pythonpool.com/wp-content/uploads/2022/03/1-83.png)
%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 = 10b = 11c = a + bprint("%d + %d = %d" % (a,b,c))
![Demystifying the Secrets of Python %d (2) Demystifying the Secrets of Python %d (2)](https://i0.wp.com/www.pythonpool.com/wp-content/uploads/2022/03/1-84-1024x95.png)
Using %d in a loop
num_range = int(input("Enter a number:"))for i in range(num_range): print("%d" %(i**2),end=", ")
![Demystifying the Secrets of Python %d (3) Demystifying the Secrets of Python %d (3)](https://i0.wp.com/www.pythonpool.com/wp-content/uploads/2022/03/1-85-1024x95.png)
Trending:
[Fixed] typeerror can’t compare datetime.datetime to datetime.date
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 = 10b = 11c = a + b# using f-stringsprint(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.
![Demystifying the Secrets of Python %d (4) Demystifying the Secrets of Python %d (4)](https://i0.wp.com/www.pythonpool.com/wp-content/uploads/2022/03/1-91-1024x84.png)
Example 2:
number, count = 5, 0while 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.
![Demystifying the Secrets of Python %d (5) Demystifying the Secrets of Python %d (5)](https://i0.wp.com/www.pythonpool.com/wp-content/uploads/2022/03/1-93-1024x186.png)
Popular now
[Fixed] nameerror: name Unicode is not defined
Formatting strings using the str.format method
Example 1:
a = 10b = 11c = a + b# usign format methodprint("{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.
![Demystifying the Secrets of Python %d (6) Demystifying the Secrets of Python %d (6)](https://i0.wp.com/www.pythonpool.com/wp-content/uploads/2022/03/1-92-1024x84.png)
Example 2:
number, count = 0, 5while count > number: print("Count: {}".format(count)) count -= 1
The above example code prints the formatted string with decreasing value of count till the number.
![Demystifying the Secrets of Python %d (7) Demystifying the Secrets of Python %d (7)](https://i0.wp.com/www.pythonpool.com/wp-content/uploads/2022/03/1-94-1024x186.png)
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))
![Demystifying the Secrets of Python %d (8) Demystifying the Secrets of Python %d (8)](https://i0.wp.com/www.pythonpool.com/wp-content/uploads/2022/03/1-89-1024x95.png)
Recommended Reading | Demystifying the Secrets of Python %s
%d
birthyear = int(input("Enter birth year:"))print("You're %d years old." %(2022-birthyear))
![Demystifying the Secrets of Python %d (9) Demystifying the Secrets of Python %d (9)](https://i0.wp.com/www.pythonpool.com/wp-content/uploads/2022/03/1-90-1024x118.png)
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 Templatetemp = Template('Hello, $name!')print(temp.substitute(name = 'Kisuke'))
![Demystifying the Secrets of Python %d (10) Demystifying the Secrets of Python %d (10)](https://i0.wp.com/www.pythonpool.com/wp-content/uploads/2022/03/1-88-1024x95.png)
Trending
[Solved] runtimeerror: cuda error: invalid device ordinal
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.
Trending Python Articles
- [Fixed] typeerror can’t compare datetime.datetime to datetime.dateby Namrata Gulati●January 11, 2024
- [Fixed] nameerror: name Unicode is not definedby Namrata Gulati●January 2, 2024
- [Solved] runtimeerror: cuda error: invalid device ordinalby Namrata Gulati●January 2, 2024
- [Fixed] typeerror: type numpy.ndarray doesn’t define __round__ methodby Namrata Gulati●January 2, 2024