温馨提示×

python字符串简单加密怎么实现

小亿
87
2024-04-08 10:55:39
栏目: 编程语言

可以使用简单的凯撒密码来对字符串进行加密。以下是一个使用凯撒密码实现字符串加密和解密的示例代码:

def encrypt(text, shift):
    encrypted_text = ""
    for char in text:
        if char.isalpha():
            if char.islower():
                encrypted_text += chr((ord(char) - ord('a') + shift) % 26 + ord('a'))
            elif char.isupper():
                encrypted_text += chr((ord(char) - ord('A') + shift) % 26 + ord('A'))
        else:
            encrypted_text += char
    return encrypted_text

def decrypt(encrypted_text, shift):
    return encrypt(encrypted_text, -shift)

# 测试加密和解密
text = "Hello, World!"
shift = 3
encrypted_text = encrypt(text, shift)
decrypted_text = decrypt(encrypted_text, shift)

print("Original text:", text)
print("Encrypted text:", encrypted_text)
print("Decrypted text:", decrypted_text)

在上面的示例代码中,encrypt函数将输入的字符串进行加密,decrypt函数将加密后的字符串进行解密。您可以根据需要更改shift的值来改变加密和解密的偏移量。

0