Skip to content

Instantly share code, notes, and snippets.

@Allstreamer
Created June 6, 2021 19:58
Show Gist options
  • Save Allstreamer/ef859b2232c0d6e5880c917159427331 to your computer and use it in GitHub Desktop.
Save Allstreamer/ef859b2232c0d6e5880c917159427331 to your computer and use it in GitHub Desktop.
Swaps letters within words
import random
import re
#Text to be Encoded
text = "This is a test sentance this should come out garbled but readable"
#Regex to strip out any special characters
regex = re.compile('[^a-zA-Z ]')
cleaned = regex.sub('', text)
#Spliting string into array of all words in input
split = cleaned.split(" ")
#Loop over every word
for x,value in enumerate(split):
#If is long enough to swap middle letters
if len(value) > 3:
# Only loop from 1 to one before last
# using -2 since -1 is the last and -2 is before last
for i in range(1,len(value)-2):
# i is first character to swap
# swap_index is second character to swap
swap_index = random.randint(1,len(value)-2)
# Convert letters to array since
# String is imutable
letters = list(split[x])
# Temporary storage so we don't lose first char
# When swapping
temp = letters[i]
# Swaping Letters
letters[i] = letters[swap_index]
letters[swap_index] = temp
# Reconecting split lettters into string to
# Override old string
letters = "".join(letters)
# Putting string back into words list
split[x] = letters
# Joining Words back into string from array to print
print(" ".join(split))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment