编写一个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
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
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]
Run Code Online (Sandbox Code Playgroud)
我想我可能需要将列表更改为字符串或整数来执行此操作,但我不知道该怎么做.
cho*_*own 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
Run Code Online (Sandbox Code Playgroud)
请注意,根据 2.7 的 Python 标准库文档,在 Python 3 发布后,使用 % 格式化操作的做法即将被淘汰。这是有关字符串方法的文档;看一下str.format。
“新方法”是:
output.append("{:02}".format(number))
Run Code Online (Sandbox Code Playgroud)