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

a = "Hello;World;"

expected output

"Hello;World"

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

"Hello-World;"

3 Answers

2
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;
1
Pushpesh Kumar Rajwanshi On

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

\B;|;\B

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,

\b;\b

Regex Demo 2

1
Devesh Kumar Singh On

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

a = "Hello;World;"
print(a.strip(';'))
#Hello;World