String encryption in python can be done in two ways, either by using the library cryptography or through rsa. In both the case you need to first install the specific library using pip install command.
The basic difference in both is the encryption methodology.
Method 1 : Using cryptography
from cryptography.fernet import Fernet
str = "sample string"
encryption_key = Fernet.generate_key()
fernet = Fernet(encryption_key)
encrypt_str = fernet.encrypt(str.encode())
print("original string: ", str)
print("encrypted string: ", encrypt_str)
decrypt_str = fernet.decrypt(encrypt_str).decode()
print("decrypted string: ", decrypt_str)
Method 2 : Using rsa
import rsa
encryption_key_public, encryption_key_private = rsa.newkeys(512)
str = "sample string"
encrypt_str = rsa.encrypt(str.encode(), encryption_key_public)
print("original string: ", str)
print("encrypted string: ", encrypt_str)
decrypt_str= rsa.decrypt(encrypt_str, encryption_key_private).decode()
print("decrypted string: ", decrypt_str)
Just an additional information, using RSA is more safe and secure than using base cryptography. But anyways this depends on the severity of the application where this is to be used.