【问题标题】:How do I write a function that takes a string, codes it in number and return the number as a string in Python?如何编写一个接受字符串的函数,将其编码为数字并在 Python 中将数字作为字符串返回?
【发布时间】:2020-09-04 04:07:36
【问题描述】:

我尝试编写一个函数,它接收一个字符串,并打印编码文本,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)

【问题讨论】:

    标签: python-3.x string function numbers


    【解决方案1】:

    您需要调用该函数并返回完整的编码。

    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.
    

    【讨论】:

    • 谢谢。我修复了它,它可以工作。但是,如何修改代码以使标点符号编码为 999?
    猜你喜欢
    • 2022-11-15
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多