JR34
JR34

Reputation: 109

place a 0 in front of numbers in a list if they are less than ten (in python)

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

Currently I have my code working to make a list of all the number, but I cannot get it to add a 0 in front of the single digit numbers.

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 output 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 am not sure how to do that.

Upvotes: 5

Views: 17183

Answers (4)

chown
chown

Reputation: 52738

Or, use the built in function designed to do this - 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

Upvotes: 11

Ben
Ben

Reputation: 71440

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))

Upvotes: 6

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 has a string formatting operation [docs] 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() [docs] 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

Upvotes: 4

Michael Hoffman
Michael Hoffman

Reputation: 34324

output.append("%02d" % number) should do it. This uses Python string formatting operations to do left zero padding.

Upvotes: 12

Related Questions