How to scramble the words in a sentence - Python

user3341166 picture user3341166 · Mar 4, 2014 · Viewed 18.4k times · Source

I have created the following code to scramble the letters in a word (except for the first and last letters), but how would one scramble the letters of the words in a sentence; given the input asks for a sentence instead of a word. Thank you for your time!

import random

def main():
    word = input("Please enter a word: ")
        print(scramble(word)) 

def scramble(word):
    char1 = random.randint(1, len(word)-2)
    char2 = random.randint(1, len(word)-2)
    while char1 == char2:
        char2 = random.randint(1, len(word)-2)
    newWord = ""

    for i in range(len(word)):
        if i == char1:
            newWord = newWord + word[char2]
        elif i == char2:
        newWord = newWord + word[char1]

        else:

            newWord = newWord + word[i]

    return newWord

main()

Answer

William McBrine picture William McBrine · Mar 4, 2014

May I suggest random.shuffle()?

def scramble(word):
    foo = list(word)
    random.shuffle(foo)
    return ''.join(foo)

To scramble the order of words:

words = input.split()
random.shuffle(words)
new_sentence = ' '.join(words)

To scramble each word in a sentence, preserving the order:

new_sentence = ' '.join(scramble(word) for word in input.split())

If it's important to preserve the first and last letters as-is:

def scramble(word):
    foo = list(word[1:-1])
    random.shuffle(foo)
    return word[0] + ''.join(foo) + word[-1]