问题描述
我试图编写一个接受字符串的函数,并打印编码的文本,其中a'为1,b为2,...,z为26。输出应为字符串,字母之间用“。”分隔。例如,encode(“ Hello!”)应该打印出“ 8.5.12.12.15.999”。这是我的代码,但是它不起作用,我也不知道为什么。运行代码时,最后什么都没打印。
def encode(text = input("Enter a text below please: ")):
tx = ""
text = text.lower()
text = "".join(text.split())
for x in range(0,len(text)):
conv_char = ord(text[x]) - 96
if conv_char > 0 and conv_char <= 26:
tx += str(conv_char) + "."
return(tx)
print(tx)
解决方法
您需要调用该函数并返回完整的编码。
def encode(text = input("Enter a text below please: ")):
tx = ""
text = text.lower()
text = "".join(text.split())
for x in range(0,len(text)):
conv_char = ord(text[x]) - 96
if conv_char > 0 and conv_char <= 26:
tx += str(conv_char) + "."
elif text[x] in [chr(c) for c in range(33,48)]:
tx += '999.'
return(tx)
# print(tx)
print(encode())
输出
Enter a text below please: hello!
8.5.12.12.15.999.