如何在python中环绕字符串

2024-05-17 17:19:03 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在尝试制作我自己版本的ROT13密码,我想把一个字符串包装成下一个字符。你知道吗

string = 'abcdefghijklmnopqrstuvwxyz'
# 'u' to 'h' and 'a' to 'n'

例如,如果角色是“u”,我将如何让角色在前面走13步?
最后会变成“h”。你知道吗

我不知道该看什么,因为我不擅长文字和解释。你知道吗


Tags: andto字符串版本角色密码string字符
3条回答

步骤如下:

1)确定“u”的索引

alphabet =  'abcdefghijklmnopqrstuvwxyz'  
index_of_u = alphabet.index('u')

2)使用模运算符计算:

offset_index = (index_of_u + 13) % 27

3)查找目标

target_char = alphabet[offset_index]

您可以使用模运算符,称为%。它给你的结果是两个数除的余数。你知道吗

例如,5%10是5,18%10是8。你知道吗

找到角色的位置:

pos = string.find('u')

你向前看:

pos += 13

找到正确的位置:

pos %= len(string)

然后打印出来:

print(string[pos])

当然,你可以写得更简洁:

print(string[(string.find('u')+13)%len(string)])

可以使用字母表的片段来创建查找字典。你知道吗

from string import ascii_lowercase
s = ascii_lowercase

rot13 = dict(zip(s, s[13:]+s[:13]))

>>> rot13
{'a': 'n', 'b': 'o', 'c': 'p', 'd': 'q', 'e': 'r', 'f': 's', 'g': 't', 'h': 'u', 'i': 'v', 'j': 'w', 'k': 'x', 'l': 'y', 'm': 'z', 'n': 'a', 'o': 'b', 'p': 'c', 'q': 'd', 'r': 'e', 's': 'f', 't': 'g', 'u': 'h', 'v': 'i', 'w': 'j', 'x': 'k', 'y': 'l', 'z': 'm'}
>>> 

相关问题 更多 >