微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我该如何编写一个接受字符串,以数字编码并以Python形式将数字返回为字符串的函数?

如何解决我该如何编写一个接受字符串,以数字编码并以Python形式将数字返回为字符串的函数?

我试图编写一个接受字符串的函数,并打印编码的文本,其中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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。