I am doing a problem from Automate the Boring Stuff, trying to imitate the strip() method using regex. I have pretty much figured it out, works with whitespace and a specific word I want removed. But when removing a specific keyword from the end of a string, it always cuts the last letter of the string off, can anyone help me figure out why?
def strip_func(string, *args):
strip_regex = re.compile(r'^(\s+)(.*?)(\s+)$')
mo = strip_regex.findall(string)
if not mo:
rem = args[0]
remove_regex = re.compile(rf'({rem})+(.*)[^{rem}]')
remove_mo = remove_regex.findall(string)
print(remove_mo[0][1])
else:
print(mo[0][1])
So if no second argument is passed then the function deletes whitespace from either side of the string, I used this string to test that:
s = ' This is a string with whitespace on either side '
Otherwise it deletes the keyword, kind of like the strip function. Eg:
spam = 'SpamSpamBaconSpamEggsSpamSpam'
strip_func(spam, 'Spam')
Output:
BaconSpamEgg
So missing the 's' at the end of Eggs, same thing happens with every string I try. Thanks in advance for the help.
rf'({rem})+(.*)[^{rem}]'is just wrong, you cannot negate a sequence of chars with a negated character class. Userf'({rem})+(.*?)(?={rem}|$)'def strip_func(string, *args): return re.sub(rf'^(?:{re.escape(args[0])})+(.*?)(?:{re.escape(args[0])})+$', r'\1', string, flags=re.S). See ideone.com/6jHH68