Scherf Scherf - 2 years ago 94
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.

Answer Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download