python字符串簡(jiǎn)單加密怎么實(shí)現(xiàn)

小億
94
2024-04-08 10:55:39

可以使用簡(jiǎn)單的凱撒密碼來(lái)對(duì)字符串進(jìn)行加密。以下是一個(gè)使用凱撒密碼實(shí)現(xiàn)字符串加密和解密的示例代碼:

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)

# 測(cè)試加密和解密
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函數(shù)將輸入的字符串進(jìn)行加密,decrypt函數(shù)將加密后的字符串進(jìn)行解密。您可以根據(jù)需要更改shift的值來(lái)改變加密和解密的偏移量。

0