首页 > 解决方案 > python string.split() 和循环

问题描述

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

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 上尝试了视频我可能真的很愚蠢

标签: pythonstringfor-loop

解决方案


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

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]

你也可以迭代内联的东西——这叫做理解。所以要转换你的字符串,你可以这样做而不是使用for循环:

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

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


推荐阅读