The following function will scramble a string, preserving spaces that separate the words, and return the result. I used this for a word game that scrambled words and phrases, which a player then attempted to descramble. For example, scrambling the following string: "teenage mutant ninja turtles" would return "etegnae tamtnu jnnai urtltes"
1 2 3 4 5
import random def scramble(string): """Scramble and return a string, preserving spaces.""" return ' '.join([''.join(random.sample(word, len(word))) for word in string.split()])