Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

Change character based off of its position? Python 2.7

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 character
    return output
print shift_char(string)
'adktivep'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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_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)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...