Hi all, I have found some examples on the net but was not able to use the technique..

here is what I would like to do.

tst = 2
numOfDigits = 3
# change this to
tst2 = 002

Any help is appreciated.
Thank you.

http://www.webdotdev.com/nvd/content/view/938/99999999/1/2/
>>> print “z is (%6d)” % 175
z is ( 175)
>>> print “z is (%06d)” % 175
z is (000175)

You can use one of the built-in string functions ...

n = 2
digits = 3
ns = str(n).rjust(digits, '0')

print(ns)  # 002

You can also use format

message = "z's value is {z:0{digits}n}".format(z=2, digits=3)
print(message)

Thank you vegaseat and gribouillis. That's exactly what I wanted to know. I'm using vegaseat's method for now.

Cheers.

There is an even more specific string function ....

n = 2
digits = 3
ns = str(n).zfill(digits)

print(ns)  # 002

These string functions work with Python2 and Python3.

Gribouillis, thanks for the Python3 code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.