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
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:
- Convert floating point number to fixed point in Python
- What is %matplotlib inline and how to use ?
- Python Program to Check Given Number is Odd or Even
- Increase the cell width of the Jupyter Notebook in browser
- Add python3 kernel to jupyter IPython notebook ?
- Reset jupyter notebook theme to default theme
- How to change the default theme in Jupyter Notebook ?
- Change the Jupyter Notebook startup folder in Windows & Mac
- To run Jupyter Notebook on Windows from command line
- Check if a file or folder exists without getting exceptions ?
- Python program to find the greatest of three numbers
- Find difference between two given numbers in Python
- Find which users belongs to a specific group in linux
- Embed HTML within IPython Notebook
- Check if Python Object is a Number ?
- Remove non-numeric characters from string in Python
- Print Patterns β Pyramid, Triangle using Star in Python
- Convert negative to positive number in Python
- TypeError: a bytes-like object is required, not βstrβ β Python3
- Extract numbers from a string in python
- Java String substring() example program