Scrambled words =============== Exercise -------- .. interactive_code_block:: :caption: Shuffle all letters except the first and last one of each word in a sentence from random import shuffle # Use a string to define which characters are punctuation marks punctuation_marks = '.:,;!?' def scramble(word): # Check if last item of that list is a punctuation mark has_puncuation_mark = word[-1] in punctuation_marks # Only scramble words consist have more than 3 characters if len(word) - has_puncuation_mark > 3: # Convert the string to list of strings characters = list(word) # Create a second list with the inner characters inner_characters = characters[1:-1 - has_puncuation_mark] # Check if inner_characters consists of different characters if len(set(inner_characters)) > 1: # Shuffle the list in place shuffle(inner_characters) # Replace the inner characters with the shuffled version characters[1:(-1 - has_puncuation_mark)] = inner_characters # Convert the list of strings to a string word = ''.join(characters) return word sentence = 'According to a researcher at Cambridge University, it doesn\\'t matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place.' words = sentence.split() scrambled_words = [scramble(word) for word in words] scrambled_sentence = ' '.join(scrambled_words) print(scrambled_sentence) """ The Significance of Letter Position in Word Recognition PhD Thesis, 1976, Nottingham University, by Graham Rawlinson https://www.mrc-cbu.cam.ac.uk/people/matt.davis/cmabridge/rawlinson/ Psycholinguistic "research" from the internet https://www.mrc-cbu.cam.ac.uk/people/matt.davis/cmabridge/ """