# Regular expressions in Python

## Objective

The Python programming language provides numerous libraries, including one dedicated to regular expressions, which can be helpful for text manipulation, particularly if you are not familiar with utilities like [*sed*](https://docs.redaction-technique.org/en/tutorials/sed-text-editing/) or *awk*.

The following code demonstrates how to reverse the order of words in a sentence, inspired by the famous line from *Le Bourgeois gentilhomme*:

```python
#!/usr/bin/env python3
# coding: utf-8

"""
Prompts the user to type in M. Jourdain's line and
displays a variant. This works only with the following line
or with the same number of words entered between quotation marks:

"Belle marquise, vos beaux yeux me font mourir d'amour."
"""

# Import the regular expression library.
import re

# Prompt the user to enter the line and store it in a variable.
original_text = input('Enter M. Jourdain\'s line in quotation marks: ')

# Remove the period from the line.
original_text_without_period = original_text.strip('.')

# Convert the string to a list of words.
shuffled_text = re.split(' ', original_text_without_period)

# Initialize a variable containing an empty string.
final_text = ''

# After verifying that the line contains 9 words, display the first
# word of the modified line, with a capital letter.
if len(shuffled_text) == 9:
    # A loop adds to the initially empty string the words of
    # M. Jourdain's line, except for the first and last, in the desired order.
    for i in [7, 5, 6, 0, 1, 2, 3]:
        final_text += ' ' + shuffled_text[i].lower()

    # Display the final text, followed by a period.
    print(shuffled_text[8].capitalize() + final_text + ' ' +
          shuffled_text[4].lower() + '.')

else:
    print('The line must be exactly nine words long.')
```

## Related articles

- [Create different documents from the same sources using Jinja](https://docs.redaction-technique.org/en/tutorials/conditional-text-jinja/)
- [Automatically insert data into a reStructuredText file](https://docs.redaction-technique.org/en/tutorials/auto-insert-data-restructuredtext/)
- [The Raspberry Pi 3 as a documentation platform](https://docs.redaction-technique.org/en/tutorials/raspberry-pi-documentation-platform/)

---

Source: https://docs.redaction-technique.org/en/tutorials/python-regular-expressions/
