Reputation: 1539
I want to remove special characters from start or end of string,
@Can't&
Using regular expression and I've tired,
`[^\w\s]`
But this regular expression removes '
which is inside the word and return below word,
Cant
Can't seem to wrap my head around this any ideas would be highly appreciated.
Upvotes: 1
Views: 544
Reputation: 14751
Can be simplified like this:
res = re.sub(r'^\W+|\W+$', '', txt)
Upvotes: 3
Reputation: 92894
Use the following approach (using regex alternation ..|..
):
import re
s = "@Can't&"
res = re.sub(r'^[^\w\s]+|[^\w\s]+$', '', s)
print(res) # Can't
Upvotes: 2