Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in python how do I convert a single digit number into a double digits string?

So say i have

a = 5

i want to print it as a string '05'

like image 822
Joe Schmoe Avatar asked Aug 17 '10 18:08

Joe Schmoe


People also ask

How do you convert a digit to a string in Python?

In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string.

How do I print 2 o2 in Python?

zfill(2) will return x as '02' for the month of feb.

How do you convert digits to words in Python?

num2words module in Python, which converts number (like 34) to words (like thirty-four). Also, this library has support for multiple languages. In this article, we will see how to convert number to words using num2words module.


2 Answers

In python 3.6, the fstring or "formatted string literal" mechanism was introduced.

f"{a:02}" 

is the equivalent of the .format format below, but a little bit more terse.


python 3 before 3.6 prefers a somewhat more verbose formatting system:

"{0:0=2d}".format(a) 

You can take shortcuts here, the above is probably the most verbose variant. The full documentation is available here: http://docs.python.org/3/library/string.html#string-formatting


print "%02d"%a is the python 2 variant

The relevant doc link for python2 is: http://docs.python.org/2/library/string.html#format-specification-mini-language

like image 128
jkerian Avatar answered Sep 20 '22 15:09

jkerian


a = 5 print '%02d' % a # output: 05 

The '%' operator is called string formatting operator when used with a string on the left side. '%d' is the formatting code to print out an integer number (you will get a type error if the value isn't numeric). With '%2d you can specify the length, and '%02d' can be used to set the padding character to a 0 instead of the default space.

like image 44
tux21b Avatar answered Sep 19 '22 15:09

tux21b