Place A 0 In Front Of Numbers In A List If They Are Less Than Ten (in Python)
Solution 1:
output.append("%02d" % number)
should do it. This uses Python string formatting operations to do left zero padding.
Solution 2:
Or, use the built in function designed to do this - zfill()
:
defword ():
# could just use a str, no need for a list:
output = ""
input = raw_input("please enter a string of lowercase characters: ").strip()
for character ininput:
number = ord(character) - 96# and just append the character code to the output string:
output += str(number).zfill(2)
# print outputreturn output
print word()
please enter a string of lowercase characters: home
08151305
Solution 3:
output = ["%02d" % n for n inoutput]
printoutput
['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26']
Python has a string formatting operation that works much like sprintf
in C and other languages. You give your data as well as a string representing the format you want your data it. In our case, the format string ("%02d"
) just represents an integer (%d
) that is 0
-padded up to two characters (02
).
If you just want to display the digits and nothing else, you can use the string .join()
method to create a simple string:
print" ".join(output)
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Solution 4:
Note, after the release of Python 3 using % formatting operations is on the way out, according to the Python standard library docs for 2.7. Here's the docs on string methods; have a look at str.format
.
The "new way" is:
output.append("{:02}".format(number))
Post a Comment for "Place A 0 In Front Of Numbers In A List If They Are Less Than Ten (in Python)"