This shows the code for one simple crypt of text by swapping two adjoining characters each. You can make that more complex if you like. Can also be used for one nice riddle.
Encrypt and Decrypt with the Swap Crypt
''' crypt_swap.py
encrypt and decrypt text using the swap of
2 adjoining characters in given text string
Python27 and Python32 work with this
'''
def swap_crypt(s):
"""
this function will encrypt/decrypt string s
"""
# change string to mutable list of characters
mylist = list(s)
# iterate the list with step=2
for k in range(0, len(mylist), 2):
if len(mylist) > k + 1:
# do tuple swap of 2 items each in the list
mylist[k], mylist[k+1] = mylist[k+1], mylist[k]
# change list back to string
return ''.join(mylist)
str_original = 'met me tomorrow noon at the train station'
# encrypt the string
str_encrypted = swap_crypt(str_original)
print("Original string:")
print(str_original)
print('-'*50)
print("Encrypted String:")
print(str_encrypted)
print('-'*50)
# decrypt the encrypted string sending it to the function again
str_decrypted = swap_crypt(str_encrypted)
print("Decrypted String:")
print(str_decrypted)
'''my output -->
Original string:
met me tomorrow noon at the train station
--------------------------------------------------
Encrypted String:
em temt moroor wonnoa tht ertia ntstaoin
--------------------------------------------------
Decrypted String:
met me tomorrow noon at the train station
'''
bumsfeld 413 Nearly a Posting Virtuoso
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.