Python:去除通配符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18533636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:58:21  来源:igfitidea点击:

Python: strip a wildcard word

pythonregexstringwildcard

提问by aldorado

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:

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

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)

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

采纳答案by falsetru

Use re.sub(pattern, '', original_string)to remove matching part from original_string:

用于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'

BTW, you are misunderstanding str.lstrip:

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

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

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

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

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