Home > database >  How to replace only part of a word using re.sub() in Python?
How to replace only part of a word using re.sub() in Python?

Time:09-15

If I had a body of text and wanted to replace "ion" or "s" with nothing but keep the rest of the word (so if the word is reflection it should output reflect), how would I go about that? I have tried:

new_llw = re.sub(r'[a-z] ion', "", llw)
print(new_llw)

which replaces the whole word, and I tried

if re.search(r'[a-z] ion', "", llw) is True:
    re.sub('ion', '', llw)

print(llw)

which gives me and error

TypeError: unsupported operand type(s) for &: 'str' and 'int'

CodePudding user response:

For the ion replacement, you may use a positive lookbehind:

inp = "reflection"
output = re.sub(r'(?<=\w)ion\b', '', inp)
print(output)  # reflect
  • Related