如果列表中的数字小于十,则在列表中的数字前放置一个0(在python中) [英] place a 0 in front of numbers in a list if they are less than ten (in python)
问题描述
编写一个Python程序,该程序将要求用户输入一个小写字母的字符串,然后打印其相应的两位数代码.例如,如果输入为"
home
",则输出应为"08151305
".
目前,我正在执行我的代码以列出所有数字,但是我无法 使其在单位数字前面添加0.
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
这是我得到的输出:
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]
我认为我可能需要将列表更改为字符串或整数才能执行此操作,但是 我不确定该怎么做.
output.append("%02d" % number)
应该做到这一点.这使用Python 字符串格式化操作进行左零填充. /p>
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.
output.append("%02d" % number)
should do it. This uses Python string formatting operations to do left zero padding.
这篇关于如果列表中的数字小于十,则在列表中的数字前放置一个0(在python中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!