[英]How to check if a value exists in a list, and store the elements that include it in variables
我正在尝试制作一个加密器,它将字母移动 3 次(因此 A 变为 D,B 变为 E 等)然后 X 回到 A,Y 到 B,Z 到 C。 我正在使用 ASCII 值来移动它们。 我正在尝试查看列表的任何部分是否具有 X、Y 或 Z 的 ASCII 值,如果是,则将该元素更改回 A、B 或 C 的 ASCII 值。 我知道您可以检查列表中是否有值,但是我如何实际获取该值并更改它? 这是我正在尝试做的事情:
def encrypt(userInput):
#Find Ascii Value of plaintext
asciiValue = [ord(c) for c in userInput]
#Convert Ascii value (list) into integers
intAscii = [int(x) for x in asciiValue]
encryptedAscii = [n + 3 for n in intAscii]
if '120' in encryptedAscii:
encryptedAscii = '97'
elif '121' in encryptedAscii:
encryptedAscii = '98'
elif '122' in encryptedAscii:
encryptedAscii = '99'
else:
encryptedOutput = ''.join(chr(v) for v in encryptedAscii)
return encryptedOutput
谢谢!
您实际上不需要分别检查x, y, z
。 只需使用模运算符( %
),因此如果溢出,它将返回a, b, c
:
def encrypt(userInput):
# Find Ascii Value of plaintext
asciiValue = [ord(c) for c in userInput]
# Convert Ascii value (list) into integers
intAscii = [int(x) - 97 for x in asciiValue]
encryptedAscii = [(n + 3) % 26 + 97 for n in intAscii]
encryptedOutput = ''.join(chr(v) for v in encryptedAscii)
return encryptedOutput
from string import ascii_lowercase
print(encrypt(ascii_lowercase))
Output:
defghijklmnopqrstuvwxyabc
使用ord
和chr
很好,但还有一种更简单的方法: str.maketrans和str.translate :
from string import ascii_uppercase as ABC, ascii_lowercase as abc
def encrypt(text, tr):
return text.translate(tr)
# join translation dicts for ABCD and abcs to
# create mapping from 2 strings of equal lenght,
# first is "from" second is "to" mapping:
tr = {**str.maketrans(abc, abc[3:]+abc[:3]), # lower case a-z
**str.maketrans(ABC, ABC[3:]+ABC[:3])} # upper case A-Z
text = "ABCDEFGXYZabcdefgxyz"
print(text, " => ", encrypt(text,tr))
Output:
ABCDEFGXYZabcdefgxyz => DEFGHIJABCdefghijabc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.