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:
- Split the text with
white spaces
andpunctutations
. - Check all parts, if the last character is
r
or not. - If it was equal to
r
, add a characterh
to that part. - 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.