Python string format integer | Example code

Python’s new-style formatting allows for rearranging the order of display without changing the arguments. Of course, it is also possible to format integers (numbers).

Python string format integer example

Simple example code.

# old
print('%d' % (100,))

# New
print('{:d}'.format(100))

Output:

Python string format integer

Format string to integer with leading zero Python

res = str(1).zfill(2)  # 1 will be '01'
print(res)

res = str(23).zfill(4)  # 23 will be '0023'
print(res)

Output:

01
0023

Format leading 0

print("{:02d}".format(1))

Output: 01

Do comment if you have any doubts and suggestions on this Python string format topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.