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.
Python code
20 linesdef 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
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
- Use `re.sub` with a callback function to replace matched words in one pass.
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.