Put 0 in front of the numbers in the list if they are less than ten (in python)

Write a Python program that asks the user to enter a string of lowercase characters, and then print the corresponding two-digit code. For example, if the input is " home", the output should be " 08151305".

Currently my code is working for me to compile a list of the whole number, but I cannot get it to add 0 in front of numbers with one digit.

def word ():
    output = []
    input = raw_input("please enter a string of lowercase characters: ")
    for character in input:
        number = ord(character) - 96
        output.append(number)
    print output

This is the result I get:

word()
please enter a string of lowercase characters: abcdefghijklmnopqrstuvwxyz
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]

I think I may need to change the list to a string or to integers to do this, but I'm not sure how to do this.

+5
source share
4 answers

output.append("%02d" % number) . Python , .

+11

, - zfill():

def word ():
    # could just use a str, no need for a list:
    output = ""
    input = raw_input("please enter a string of lowercase characters: ").strip()
    for character in input:
        number = ord(character) - 96
        # and just append the character code to the output string:
        output += str(number).zfill(2)
    # print output
    return output


print word()
please enter a string of lowercase characters: home
08151305
+10
output = ["%02d" % n for n in output]
print 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']

Python [docs] , sprintf C . , , , . ("%02d") (%d), 0 - (02).

If you just want to display numbers and nothing else, you can use the .join() [ docs ] line to create a simple line:

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
+4
source

Please note that after the release of Python 3 using% output formatting, according to the standard Python library docs for 2.7. Here are the docs on string methods ; take a look at str.format.

"New way":

output.append("{:02}".format(number))
+4
source

All Articles