[python] 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'

This question is related to python string numbers digits

The answer is


Based on what @user225312 said, you can use .zfill() to add paddng to numbers converted to strings.

My approach is to leave number as a number until the moment you want to convert it into string:

>>> num = 11
>>> padding = 3
>>> print(str(num).zfill(padding))
011

Branching off of Mohommad's answer:

str_years = [x for x in range(24)]
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

#Or, if you're starting with ints:
int_years = [int(x) for x in str_years]

#Formatted here
form_years = ["%02d" % x for x in int_years]

print(form_years)
#['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']


>>> print '{0}'.format('5'.zfill(2))
05

Read more here.


df["col_name"].str.rjust(4,'0')#(length of string,'value') --> ValueXXX --> 0XXX  
df["col_name"].str.ljust(4,'0')#(length of string,'value') --> XXXValue --> XXX0

In Python 3.6 you can use so called f-strings. In my opinion this method is much clearer to read.

>>> f'{a:02d}'
'05'

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.


>>> a=["%02d" % x for x in range(24)]
>>> a
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
>>> 

It is that simple


In Python3, you can:

print("%02d" % a)

This is a dumb solution but I was getting type errors with the other solutions above. So if all else fails, yolo:

images3digit = []

for i in images:
        if len(i)==1:
            i = '00'+i
            images3digit.append(i)
        elif len(i)==2:
            i = '0'+i
            images3digit.append(i)
        elif len(i)==3:
            images3digit.append(i)

If you are an analyst and not a full stack guy, this might be more intuitive:

[(str('00000') + str(i))[-5:] for i in arange(100)]

breaking that down, you:

  • start by creating a list that repeats 0's or X's, in this case, 100 long, i.e., arange(100)

  • add the numbers you want to the string, in this case, numbers 0-99, i.e., 'i'

  • keep only the right hand 5 digits, i.e., '[-5:]' for subsetting

  • output is numbered list, all with 5 digits


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to digits

C++ - how to find the length of an integer Gets last digit of a number Sum the digits of a number Get number of digits with JavaScript How do I separate an integer into separate digits in an array in JavaScript? C: how to break apart a multi digit number into separate variables? Show a leading zero if a number is less than 10 How to tell if string starts with a number with Python? in python how do I convert a single digit number into a double digits string? Controlling number of decimal digits in print output in R