Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: strip a wildcard word

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)

like image 735
aldorado Avatar asked Aug 30 '13 13:08

aldorado


People also ask

How does Python handle wildcards?

In Python, we can implement wildcards using the regex (regular expressions) library. The dot . character is used in place of the question mark ? symbol.

How do you strip text from a string in Python?

Use the . strip() method to remove whitespace and characters from the beginning and the end of a string. Use the . lstrip() method to remove whitespace and characters only from the beginning of a string.

What is TXT Strip () in Python?

strip() is an inbuilt function in Python programming language that returns a copy of the string with both leading and trailing characters removed (based on the string argument passed).


1 Answers

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'
like image 55
falsetru Avatar answered Oct 24 '22 16:10

falsetru