.strip() function taking off first letter of string when it shouldn't

Advertisements

I have a string that I’m trying to strip the last camel cased word off if it matches any of these words specified in the regex by doing

my_string = 'myFileCins'
my_string.strip("(Cins)?(V2)?(Fitch)?$")

This returns ‘myFile’ which is fine. However it looks like if the string starts with the letter "c" (based on my testing) it will strip off the first letter of the string as well.

So:

my_string = 'cyFile'
my_string.strip("(Cins)?(V2)?(Fitch)?$")

will return ‘yFile’. I was wondering how I can fix this since I thought my regex is specified to only strip those specific whole words in the string

>Solution :

str.strip(...) for regex? It doesn’t have to do a anything with regex. Use re.sub instead!

my_string = 'cyFile'
pattern = r'\b(Cins|V2|Fitch)$'

result = re.sub(pattern, '', my_string)

Leave a ReplyCancel reply