Reverse Words in a Sentence While Keeping Punctuation in Python

Reverses the order of words in a sentence while leaving punctuation and spaces in their original positions using Python's re module.

Easy Python 3.9+ Aug 9, 2026 Strings & text 13 views 0 copies

Python code

20 lines
Python 3.9+
def reverse_words_preserving_punctuation(sentence: str) -> str:
    import re
    # Split into words and punctuation tokens
    tokens = re.findall(r'\w+|[^\w\s]|\s+', sentence)
    words = [t for t in tokens if re.fullmatch(r'\w+', t)]
    words.reverse()
    result_parts = []
    word_index = 0
    for token in tokens:
        if re.fullmatch(r'\w+', token):
            result_parts.append(words[word_index])
            word_index += 1
        else:
            result_parts.append(token)
    return ''.join(result_parts)


if __name__ == "__main__":
    test = "Hello, world! How are you?"
    print(reverse_words_preserving_punctuation(test))

Output

stdout
you are How world! Hello,?

How it works

The function uses re.findall with the pattern \w+|[^\w\s]|\s+ to tokenize the sentence into words, punctuation, and whitespace separately. It collects all word tokens, reverses their order, and then rebuilds the sentence by replacing each word token with the next word from the reversed list while keeping punctuation and spaces untouched. This works because the original token positions are preserved, and only the word order changes.

Common mistakes

  • Using `split()` without punctuation handling, which removes punctuation and breaks the original spacing.
  • Not using `re.fullmatch` to correctly identify word tokens, causing non-word characters to be treated as words.
  • Forgetting to import `re` inside the function if it's not imported globally.
  • Assuming the input never has multiple spaces or tabs, which causes incorrect tokenization.

Variations

  1. Use `re.sub` with a callback function to replace matched words in one pass.
  2. If punctuation is not important, a simpler `sentence.split()[::-1]` can be used, but it strips punctuation.

Real-world use cases

  • Building a text transformation tool that preserves formatting while reordering words for obfuscation or humor.
  • Preprocessing user-generated content where punctuation and whitespace must remain intact before further analysis.
  • Creating a word-level scramble feature in a word puzzle or language learning app that keeps sentence structure recognizable.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.