Replace Characters From End of String

Posted September 22, 2022 by Rohith ‐ 1 min read

Regex module `re` in python can be used to replace characters from end of the string.

sub method in re module can be used to replace the characters from end of the string.

Let’s say, we want to replace --- at the end of the string with ___

Regular expression to replace the characters from end of the string is '-+'.

It can be better explained with an example.

Example

Let’s say, we want to replace the characters from end of the string in whiletrue.live---.

import re

host = 'whiletrue.live---'
new_host = re.sub('-+$', '_', host) 

print(new_host) # 'whiletrue.live___'
quick-references python regex blog

Subscribe For More Content