Python: split wildcard

I have lines with words separated by dots. Example:

string1 = 'one.two.three.four.five.six.eight' string2 = 'one.two.hello.four.five.six.seven' 

How to use this line in python method, assigning one word as a template (because in this case, for example, the third word changes). I am thinking about regular expressions, but I don’t know if such an approach is possible, as I have in mind, in python. For instance:

 string1.lstrip("one.two.[wildcard].four.") 

or

 string2.lstrip("one.two.'/.*/'.four.") 

(I know that I can extract this with split('.')[-3:] , but I'm looking for a general way, lstrip is just an example)

+6
source share
1 answer

Use re.sub(pattern, '', original_string) to remove the corresponding 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' 

By the way, you misunderstand str.lstrip :

 >>> 'abcddcbaabcd'.lstrip('abcd') '' 

str.replace is more appropriate (of course, re.sub too):

 >>> 'abcddcbaabcd'.replace('abcd', '') 'dcba' >>> 'abcddcbaabcd'.replace('abcd', '', 1) 'dcbaabcd' 
+18
source

Source: https://habr.com/ru/post/952834/


All Articles