I have a string on unknown length, contain the characters a-z A-Z 0-9. I need to change each character using their position from Left to Right using a dictionary.
Example:
string = "aaaaaaaa"
def shift_char(text):for i in len(text):# Do Something for each characterreturn output
print shift_char(string)
'adktivep'
Alright, hopefully this is understandable, otherwise feel free to ask questions.
import random
import string# Letter pool, these are all the possible characters
# you can have in your string
letter_pool = list(string.ascii_letters + string.digits)input_string = "HelloWorld"
string_length = len(input_string)# Generate one random dictionary for each character in string
dictionaries = []for i in range(string_length):# Copy letter_pool to avoid overwriting letter_poolkeys = list(letter_pool)values = list(letter_pool)# Randomise values, (keep keys the same)random.shuffle(values)# This line converts two lists into a dictionaryscrambled_dict = dict(zip(keys, values))# Now each letter (key) maps to a random letter (value)dictionaries.append(scrambled_dict)# Initiate a fresh string to start adding characters to
out_string = ""# Loop though the loop string, record the current place (index) and character each loop
for index, char in enumerate(input_string):# Get the dictionary for this place in the stringdictionary = dictionaries[i]# Get the randomised character from the dictionarynew_char = dictionary[char]# Place the randomised character at the end of the stringout_string += new_char# Print out the random string
print(out_string)
Edit: If you want to only generate the random dictionaries once, and load them in everytime, you can serialise the dictionaries
array. My favourite is json.