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

16次阅读
没有评论

共计 741 个字符,预计需要花费 2 分钟才能阅读完成。

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

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 的值来改变加密和解密的偏移量。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-04-16发表,共计741字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)