Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Remove spaces regex

This is not necessary as we can use rstrip, lstrip, and replace.

import re

line = "  ab cd  "

res = re.sub(r'^\s+', '', line)  # leading
print(f"'{res}'")

res = re.sub(r'\s+$', '', line)  # trailing
print(f"'{res}'")


both ends:

re.sub(r'\s*(.*)\s*$', r'\1', line)  #  " abc " =>  "abc "  because of the greediness
re.sub('^\s*(.*?)\s*$', '\1', line)  #   " abc " =>  "abc"  minimal match