首页主机资讯python字符串简单加密怎么实现

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

时间2024-05-26 12:28:03发布访客分类主机资讯浏览1535
导读:可以使用简单的凯撒密码来对字符串进行加密。以下是一个使用凯撒密码实现字符串加密和解密的示例代码: def encrypt(text, shift : encrypted_text = "" for char in text:...

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

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

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: python字符串简单加密怎么实现
本文地址: https://pptw.com/jishu/668467.html
python如何去除字符串中的符号 设置background背景图片

游客 回复需填写必要信息