Strip() Function Using Regex
I slightly changed your script like this,
def strip(char, string):
if char == "": # not "stripChar"
regsp = re.compile(r'^\s+|\s+$')
stripContext = regsp.sub("", context)
return stripContext
else: # some changes are here in this else statement
stripContext = re.sub(r'^{}+|{}+$'.format(char,char), "", strip("",string))
return stripContext
print(strip(stripChar, context))
Output:
Enter character to strip: e
Enter string to strip: efdsafdsaeeeeeeeeee
fdsafdsa
You could do it like this using re.sub
import re
def strip(string, chars=' \n\r\t'):
return re.sub(r'(?:^[{chars}]+)|(?:[{chars}]+$)'.format(chars=re.escape(chars)), '', string)
It uses re.escape
, so users can enter characters like \
and [
that have meaning withing regex strings. It also uses the ^
and $
regex tokens so that only groups of matching characters at the front and end of the string are matched.
I did it that simple way and it worked for me.
import re
def my_strip(string, char=''):
regex_sub = re.sub(r'^\s+|\s+$', char, string)
return(regex_sub)