Python program to convert single digit number to double digits string

Python program to convert single digit number to double digits string

In this tutorial let’s see how to convert single digit number to double digits string in Python programming language using str.format() and old formatting techniques with examples.

Python program to convert single digit number to double digits string

Python program to convert single digit number to double digits string

The built-in string class provides options to do value formatting using the format() method. Let’s see in Custom String Formatting, how to use str.format() method to convert single digit number to double digits string.

Β 

Β 

For example,

>>> x = 5
>>> print("{0:02d}".format(x))
05

In the above example, we are using str.format() syntax. You can also try using old formatting i.e., % formatting.

In most of the cases, the str.format() syntax is similar to the old % formatting. Note, the difference between these two ways is we are using “{}” and “:” instead of “%“. For example, ‘%02d” can be translated to “{0:02d}“.

Convert using % – Formatting

The % operator is called as string formatting operator. And they are used for formatting strings. %d acts as a placeholder or a number.

Let’s see how to convert single digit number to double digit string using old formatting operator.

For example,

>>> x= 5
>>> print("%02d"%x)
05

New format Syntax – str.format()

Note, the new format syntax supports various new options. The following are some of the options supported.

Accessing arguments by position

For example,

>>> '{0}, {1}, {2}'.format('x', 'y', 'z')
'x, y, z'

Accessing arguments by name

For example,

>>> 'Point: {x}, {y}'.format(x=4, y=5)
'Point: 4, 5'
>>> p = {'x':'4', 'y':'5'}
>>> 'Point: {x}, {y}'.format(**p)
'Point: 4, 5'

For more details on other supported options please check in the following link Format Examples.

Hope it helped πŸ™‚

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments