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.
Can be simplified like this:
res = re.sub(r'^\W+|\W+$', '', txt)
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
You could just add an exception for '
in the expression:
[^\w\s']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.