Change character based off of its position? Python 2.7
<p>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.</p>

<p>Example:</p>

<pre><code>string = "aaaaaaaa"
def shift_char(text):
    for i in len(text):
        # Do Something for each character
    return output
print shift_char(string)
'adktivep'
</code></pre>

<p>Alright, hopefully this is understandable, otherwise feel free to ask questions.</p>

<pre><code>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_pool
    keys = list(letter_pool)
    values = list(letter_pool)
    # Randomise values, (keep keys the same)
    random.shuffle(values)

    # This line converts two lists into a dictionary
    scrambled_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 string
    dictionary = dictionaries[i]
    # Get the randomised character from the dictionary
    new_char = dictionary[char]
    # Place the randomised character at the end of the string
    out_string += new_char

# Print out the random string
print(out_string)
</code></pre>

<p>Edit: If you want to only generate the random dictionaries once, and load them in everytime, you can serialise the <code>dictionaries</code> array. My favourite is <a href="https://docs.python.org/3.5/library/json.html" rel="nofollow">json</a>.</p>

python python-2.7