Welcome, guest | Sign In | My Account | Store | Cart

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"

Python, 5 lines
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()])

2 comments

Chaobin Tang (ε”θΆ…ζ–Œ) 11 years, 4 months ago  # | flag

interesting, simple enough with sampling from the random module. and also nice practice in some language learning websites, as a language game.

rangga.kumal 9 years, 5 months ago  # | flag

wow very simple... but a cant understand.... soory i'm newbie