Python: strip a wildcard word
42,443
Use re.sub(pattern, '', original_string)
to remove matching part from original_string:
>>> import re
>>> string1 = 'one.two.three.four.five.six.eight'
>>> string2 = 'one.two.hello.four.five.six.seven'
>>> re.sub(r'^one\.two\.\w+\.four', '', string1)
'.five.six.eight'
>>> re.sub(r'^one\.two\.\w+\.four', '', string2)
'.five.six.seven'
BTW, you are misunderstanding str.lstrip
:
>>> 'abcddcbaabcd'.lstrip('abcd')
''
str.replace
is more appropriate (of course, re.sub, too):
>>> 'abcddcbaabcd'.replace('abcd', '')
'dcba'
>>> 'abcddcbaabcd'.replace('abcd', '', 1)
'dcbaabcd'
Author by
aldorado
Updated on November 24, 2020Comments
-
aldorado over 3 years
I have strings with words separated by points. Example:
string1 = 'one.two.three.four.five.six.eight' string2 = 'one.two.hello.four.five.six.seven'
How do I use this string in a python method, assigning one word as wildcard (because in this case for example the third word varies). I am thinking of regular expressions, but do not know if the approach like I have it in mind is possible in python. For example:
string1.lstrip("one.two.[wildcard].four.")
or
string2.lstrip("one.two.'/.*/'.four.")
(I know that I can extract this by
split('.')[-3:]
, but I am looking for a general way, lstrip is just an example) -
aldorado over 10 yearsThank you! And to your "BTW": Is there a possibility to strip only the "abcd" that are ordered in the right way? or is this a case for regex only?
-
falsetru over 10 years@aldorado,
'abcddcbaabcd'.replace('abcd', '', 1)
.1
means replace only once. -
falsetru over 10 years@aldorado, I added another code that show sample usage of
str.replace
.