How to Convert a 1-Digit Number to a 2-Digit Number in Python?

Estimated read time 1 min read

To convert a 1-digit number to a 2-digit number in Python, you can make use of string formatting or concatenation with a leading zero. Here are two approaches you can use:

  1. String Formatting:
number = 5
two_digit_number = "{:02d}".format(number)

In this approach, the "{:02d}" format specifier is used to format the number as a two-digit string with leading zeros if necessary. The 02 specifies that the resulting string should have a width of 2 characters, and the d indicates it is an integer.

  1. Concatenation with Leading Zero:
number = 7
two_digit_number = "0" + str(number) if number < 10 else str(number)

In this approach, we check if the number is less than 10. If it is, we prepend a leading zero to the string representation of the number using string concatenation. Otherwise, we simply convert the number to a string.

Both approaches achieve the same result of converting a 1-digit number to a 2-digit number. Choose the one that suits your coding style and requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply