【问题标题】:Two strings, and have the letters inputed printed what is held in the other string两个字符串,并让输入的字母打印出另一个字符串中的内容
【发布时间】:2020-01-17 19:34:48
【问题描述】:

不确定标题是否有意义或真的如何表达问题,但我想做的是用户输入一个句子,然后它会根据任何索引从另一个字符串中获取字母是并将其打印到新字符串然后打印字符串。

可能是一种更简单的方式,但如果你能解释这种方式并且更简单的方式会很酷,也许你会在看到代码后理解。

abc = "abcdefghijklmnopqrstuvwxyz"
caesar_cipher="bcdefghijklmnopqrstuvwxyza"
user = input("Enter what you want ciphered: ")
new_string = ''




print(new_string)

【问题讨论】:

    标签: python python-3.x string input


    【解决方案1】:

    使用str.translatestr.maketrans

    new_string = user.translate(str.maketrans(abc, caesar_cipher))
    

    例如:

    >>> "hello, world".translate(str.maketrans(abc, caesar_cipher))
    'ifmmp, xpsme'
    

    【讨论】:

    • 太棒了,我会确保查看相关文档!
    【解决方案2】:

    我认为你想要的是实现凯撒密码。如果您观察 Ceaser 密码是什么,它只是将每个字符移动固定数量的字符。在您的示例中,所有“a”都被“b”替换,“b”被“c”替换,依此类推。您的示例的基本版本可以这样完成:

    def encode_using_ceaser_cipher(input):
        output = ''
        for c in input:
            output += chr((ord(c) + 1)% (26 + 97))
        return output
    
    
        abc = "abcdefghijklmnopqrstuvwxyz"
        user = input("Enter what you want ciphered: ")
        new_string = encode_using_ceaser_cipher(input)
        print(new_string)
    

    要了解这条线的作用

    output += chr((ord(c) + 1)% (26 + 97))
    

    我们将存储在 c 中的字符转换为其 ascii 值,将其递增 1,然后使用 chr 将其转换回字符。但是,以这种方式将 'z' 转换回字符会导致得到一个不在 [a-z] 范围内的字符。为此,我们必须对模数运算符进行这种丑陋的破解。注意:这仅适用于小写字母 (a-z)。 希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-28
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      相关资源
      最近更新 更多