How to replace characters which are present only at the word boundary (start or end) in python?

a = "Hello;World;"

expected output


Also at later stage if I want to replace special characters only if they are present inside the word and not at boundary For example:

a = "Hello;World;"

expected output


3 Answers

Charles Landau On

Well format can handle this, of that I'm sure:

a = "Hello;World;"
a = "{}{}{}".format(a[0],a[1:-1].replace(";", "-"),a[-1])
a # Hello-World;
Pushpesh Kumar Rajwanshi On

You can use this regex to replace a special character, whose either one side is non-word boundary,


Regex Demo 1

And in case you want to replace a special character which is surrounded by word boundary from both sides, you can use this regex,


Regex Demo 2

Devesh Kumar Singh On

For the word boundary case, you can use the old string.strip with ; argument

a = "Hello;World;"