【问题标题】:python string.split() and loopspython string.split() 和循环
【发布时间】:2020-03-03 22:55:54
【问题描述】:

免责声明 我是 python 新手 我需要拆分字符串输入发送 if 到一个函数,该函数用不同的字符(如替换密码)替换字符串中的字符,但我只是不知道该怎么做

print('Welcome to the encryption protocol for top secret governemt cover ups')
string=input('whats your message?')
def encrypt(string):
    alpha = "abcdefghijklmnopqrstuvwyz"
    sub_alpha = "pokmenliuytrwqazxcvsdfgbhn"

index=0
while index < len(string):
    letter=string[index]

我不太确定我在 python 方面做得不好,这让我难倒了 3 天,现在我查看了我的课程材料并尝试了 youtube 上的视频,我可能真的很愚蠢

【问题讨论】:

    标签: python string for-loop


    【解决方案1】:

    我认为您缺少的关键知识是字符串是可迭代的。因此,您可以执行以下操作:

    for c in "FOO":
        print(c)
        # prints "F\nO\nO\n"
    

    您可以使用str.index 找到字符串中字符的索引。所以你可以像这样构建你的密文:

    alpha = "abcdefghijklmnopqrstuvwyz "
    cypher = "pokmenliuytrw qazxcvsdfgbhn"
    plaintext = "some string"
    cyphertext = ""
    for c in plaintext:
        char_index = alpha.index(c)
        cyphertext += cypher[char_index]
    

    您还可以迭代内联的东西 - 这称为 comprehension。因此,要转换您的字符串,您可以这样做而不是使用 for 循环:

    cyphertext = "".join(cypher[alpha.index(c)] for c in plaintext)
    

    上面的示例使用str.join 函数连接密文的每个字符。

    【讨论】:

    • 这很好用,尝试将其拆分为我自己的功能,谢谢
    【解决方案2】:

    这是一个解决方案,它提出问题,然后遍历每个字母,在 alpha 键中找到索引,并将其替换为等效的 sub_alpha 键。 请注意,此示例还检查它应该是小写还是大写。 编辑:如果输入字符没有有效的密码,它不会被改变。 编辑 2:扩展答案以向前和向后转换。

    alpha = "abcdefghijklmnopqrstuvwyz"
    sub_alpha = "pokmenliuytrwqazxcvsdfgbhn"
    
    def encrypt(in_char):   
        is_lower_case = in_char.islower()
        index = alpha.find(in_char.lower())
    
        if index < 0:
            return in_char
        elif is_lower_case:
            return sub_alpha[index]
        else:
            return sub_alpha[index].upper()
    
    def decrypt(in_char):
        is_lower_case = in_char.islower()
        index = sub_alpha.find(in_char.lower())
    
        if index < 0:
            return in_char
        elif is_lower_case:
            return alpha[index]
        else:
            return alpha[index].upper()
    
    print('Welcome to the encryption protocol for top secret governemt cover ups')
    input_str=input('whats your message? ')
    output_str=""
    
    for letter in input_str:
        output_str += encrypt(letter)
    
    print("Encrypted: ")
    print(output_str)
    
    input_str=""
    for letter in output_str:
        input_str+= decrypt(letter)
    
    print("Decrypted: ")
    print(input_str)
    

    【讨论】:

    • 我得到这个错误:NameError: output_str not defined
    • @irvdtcc 您没有发布错误,但我猜这是因为您没有完整的密钥,例如,如果您有空格,那么它不知道该转什么那成。我会编辑答案来解决这个问题:)
    • @irvdtcc 试试这个,更好吗?
    • @irvdtcc 我刚刚看到你的编辑。尝试使用我发布的代码,我添加了一行声明 output_str。我不只是改变了加密功能。
    • 这很好用!顺便说一句,错误是什么意思?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2017-09-11
    相关资源
    最近更新 更多