python - 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 上尝试了视频我可能真的很愚蠢
解决方案
我认为您缺少的关键知识是字符串是可迭代的。因此,您可以执行以下操作:
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函数连接密文的每个字符。
推荐阅读
- arrays - 将数组中的值复制到结构的变量中
- java - 当我们说tomcat服务器正在“运行”时是什么意思。幕后到底发生了什么
- javascript - React Redux - 提交时不会触发动作
- java - 唯一对象实例的Java Map?
- python - 我如何在数据框中划分这个文本文件?
- wordpress - 我们如何让 Wordpress 支持 .jfif 图片上传?
- react-native - 如何将数据发送到硬件上的先前路线按反应导航 5
- mongodb - MongoDB 存储 API 调用
- c# - 在 Blazor 中绑定使用 InputFile 选择的文件
- php - Opencart htaccess 以减少服务器响应时间和缓存