Scherf Scherf - 8 months ago 22
Python Question

Replace characters at end of a string

I want to use regular expressions to replace things at the start/end of all words in a file. Here are some example cases:

  1. words ending in "ing" get changed to end in "gni": clearing = cleargni

  2. words starting with "sub" get changed to start with "bus": subtract = bustract

How can I isolate these words in a list and apply the example changes?
All words are lowercase.


Use \b to make sure something is at the beginning or end of a word:

import re

sentence = "..."
converted = re.sub(r'ing\b', 'gni', re.sub(r'\bsub', 'bus', sentence))