WilliamFrog8
WilliamFrog8

Reputation: 87

strip() regex replacement clarification

I am working on the regex replacement for strip() program from the Automate the Boring Stuff with Python textbook and, since I had no idea how to even begin, I opted for Stack Overflow and found a thread with the following code :

#!python3
import re

respecchar = ['?', '*', '+', '{', '}', '.', '\\', '^', '$', '[', ']']


def regexstrip(string, _strip):
    if _strip == '' or _strip == ' ':
        _strip = r'\s'
    elif _strip in respecchar:
        _strip = r'\'+_strip'
    print(_strip) #just for troubleshooting 
    re_strip = re.compile('^'+_strip+'*(.+)'+_strip+'*$')
    print(re_strip) #just for troubleshooting 
    mstring = re_strip.search(string)
    print(mstring) #just for troubleshooting 
    stripped = mstring.group(1)
    print(stripped)

I don't understand quite a few things about this code.

The two if \ elif statements only check for the _strip argument if it's non-existent, a space or a symbol given in the respecchar list above the function. The guy claims the code works even if you put a letter as the second argument and nobody in the comment section even questions it. How come ?

The second thing I wanted to ask was about the line under the elif statement : strip = r''+_strip'
Doesn't the string end after the second quotation mark ( since it begins with only a single quotation mark ) ? How come the whole string ends only after the +_strip part of it ?

Thank you in advance !

Upvotes: 0

Views: 63

Answers (1)

John Gordon
John Gordon

Reputation: 33335

The two if \ elif statements only check for the _strip argument if it's non-existent, a space or a symbol given in the respecchar list above the function. The guy claims the code works even if you put a letter as the second argument

That's because those characters are the only ones that need special handling in a regex. If it's a plain letter, it can be used as part of the regex exactly as-is.

strip = r'\'+_strip'

That's a typo. The trailing ' shouldn't be there.

Upvotes: 1

Related Questions