繁体   English   中英

如果小于10,则在列表中的数字前放置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 字符串格式化操作来做零填充。

或者,使用设计用于执行此操作的内置函数 - 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
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有一个字符串格式化操作[ docs ] ,其工作原理与C语言和其他语言中的sprintf非常相似。 您提供数据以及表示您希望数据格式的字符串。 在我们的例子中,格式字符串( "%02d" )只表示一个整数( %d ),它是0 padded,最多两个字符( 02 )。

如果您只想显示数字.join()显示其他内容,则可以使用字符串.join() [ docs ]方法创建一个简单的字符串:

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

注意,在Python 3发布之后,使用%格式化操作正在逐步推出,根据2.7的Python标准库文档。 这是关于字符串方法的文档 ; 看看str.format

“新方式”是:

output.append("{:02}".format(number))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM