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.
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.
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.
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 { }.
zfill(2) will return x as '02' for the month of feb.
output.append("%02d" % number)
should do it. This uses Python string formatting operations to do left zero padding.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With