Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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.

like image 461
JR34 Avatar asked Oct 05 '11 04:10

JR34


People also ask

How do you put a zero before a number in Python?

zfill() Function to Display a Number With Leading Zeros in Python. The str. zfill(width) function is utilized to return the numeric string; its zeros are automatically filled at the left side of the given width , which is the sole attribute that the function takes.

How do you add leading zeros to a string in Python?

For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.

How do you use 0 in Python?

Python 0 is an indicator of the format method that you need to be replaced by the format's first (index zero) parameter. It is used to execute a string formatting operation. The formatted string argument contains a literal text or replacement fields delimited by braces { }.

How do you write o2 in Python?

zfill(2) will return x as '02' for the month of feb.


2 Answers

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

like image 59
Michael Hoffman Avatar answered Sep 20 '22 14:09

Michael Hoffman


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
like image 37
chown Avatar answered Sep 16 '22 14:09

chown