Python:删除通配符

ald*_*ado 12 python regex string wildcard

我的字符串用点分隔.例:

string1 = 'one.two.three.four.five.six.eight' 
string2 = 'one.two.hello.four.five.six.seven'
Run Code Online (Sandbox Code Playgroud)

如何在python方法中使用此字符串,将一个单词指定为通配符(因为在这种情况下,例如第三个单词变化).我正在考虑正则表达式,但不知道在python中是否可以考虑我的方法.例如:

string1.lstrip("one.two.[wildcard].four.")
Run Code Online (Sandbox Code Playgroud)

要么

string2.lstrip("one.two.'/.*/'.four.")
Run Code Online (Sandbox Code Playgroud)

(我知道我可以提取它split('.')[-3:],但我正在寻找一种通用的方法,lstrip只是一个例子)

fal*_*tru 23

用于re.sub(pattern, '', original_string)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'
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你是误会str.lstrip:

>>> 'abcddcbaabcd'.lstrip('abcd')
''
Run Code Online (Sandbox Code Playgroud)

str.replace更合适(当然,也是re.sub):

>>> 'abcddcbaabcd'.replace('abcd', '')
'dcba'
>>> 'abcddcbaabcd'.replace('abcd', '', 1)
'dcbaabcd'
Run Code Online (Sandbox Code Playgroud)

  • @aldorado,我添加了另一个代码,显示了`str.replace`的示例用法. (2认同)