Skip to content
scipython.com

P2.5.11Jumbling the letters in each word of a sentence

Write a program to take a string of text (words, perhaps with punctuation, separated by spaces) and output the same text with the middle letters shuffled randomly. Keep any punctuation at the end of words. For example, the string:

Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal.

might be rendered:

Four sorce and seevn yeras ago our fhtaers bhrogut ftroh on this cnnoientt a new noitan, cvieecond in lbrteiy, and ddicetead to the ptosoiporin that all men are cetaerd euaql.

Hint: random.shuffle shuffles a list of items in place. See Section 4.5.1 of the book.

Show solution

For example,

import random

# The text to mangle
text = """Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal."""

# Loop over all the words in the text, split on whitespace
for word in text.split():
    # We don't want any punctuation after the word, so find the last
    # alpha character (A-Z, a-z) of the word, indexed at ilast
    ilast = len(word)
    while ilast > 3:
        ilast -= 1
        if word[ilast].isalpha():
            # We've found the last alpha character
            break
    else:
        # There's no point in doing anything with words with fewer than
        # four letters in them, so print them unchanged and move on
        print(word, end=' ')
        continue

    # Get the middle letters of the word as a list and shuffle them in place
    # NB strings are immutable so we can't shuffle word[1:ilast] directly
    middle_letters = list(word[1:ilast])
    random.shuffle(middle_letters)
    # Print the reassembled word, joining the initial, middle and last letters
    print(''.join(word[0] + ''.join(middle_letters) + word[ilast:]), end=' ')

An example output is:

Four srcoe and sveen years ago our fhtares bguohrt froth on tihs cnnnoetit a new naiotn, ccinevoed in lrtieby, and dtaecdied to the pposrotoiin that all men are creeatd euaql.