Home > Software engineering >  Substituting a specific character at the end of words
Substituting a specific character at the end of words

Time:10-01

import re

text="Her sweet-natured father is constantly henpecked by his domineering wives, who rule their domains with iron fists. His wives were named Alexis, Eris, Irer, Zenith and Saunder."
text=re.sub(r'r$\b','rh',text)
print(text)

Desired output:

Her sweet-natured fatherh is constantly henpecked by his domineering wives, who rule theirh domains with iron fists. His wives were named Alexis, Eris, Irerh, Zenith and Saunderh.

Output:

Her sweet-natured father is constantly henpecked by his domineering wives, who rule their domains with iron fists. His wives were named Alexis, Eris, Irer, Zenith and Saunder.

I.e., no change has occurred in the string. Is something wrong?

CodePudding user response:

If you want to append 'h' to every words that end with 'r':

text="Her sweet-natured father is constantly henpecked by his domineering wives, who rule their domains with iron fists. His wives were named Alexis, Eris, Irer, Zenith and Saunder."

text=re.sub(r'(r)\b',r'rh',text)
print(text)

result:

Herh sweet-natured fatherh is constantly henpecked by his domineering wives, who rule theirh domains with iron fists. His wives were named Alexis, Eris, Irerh, Zenith and Saunderh.

CodePudding user response:

  1. Split the text with white spaces and punctutations.
  2. Check all parts, if the last character is r or not.
  3. If it was equal to r, add a character h to that part.
  4. Join all parts together.

Check this code below:

import re
text="Her sweet-natured father is constantly henpecked by his domineering wives, who rule their domains with iron fists. His wives were named Alexis, Eris, Irer, Zenith and Saunder."
parts = re.split("([\.\,\!\?\-\s \_])", text)
for index, part in enumerate(parts):
    if len(part) != 0 and part[-1] == 'r':
       parts[index]  = 'h'
final_text = "".join(parts[:])
print(final_text)

Result
Herh sweet-natured fatherh is constantly henpecked by his domineering wives, who rule theirh domains with iron fists. His wives were named Alexis, Eris, Irerh, Zenith and Saunderh.

  • Related