如果列表中的数字小于十,前面加0(在python中)

5 投票
4 回答
16815 浏览
提问于 2025-04-17 03:41

写一个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]

我觉得我可能需要把列表转换成字符串或者整数来实现这个,但我不太确定该怎么做。

4 个回答

6

注意,Python 3发布后,使用%格式化的操作正在逐渐被淘汰,这在Python 2.7的标准库文档中有说明。这里是关于字符串方法的文档; 可以看看 str.format

“新方法”是:

output.append("{:02}".format(number))
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
12

output.append("%02d" % number) 这个代码应该可以解决问题。它使用了Python中的一种叫做字符串格式化的操作,可以在数字前面加上零,使其变成固定的长度。

撰写回答