gpt4 book ai didi

Python:去掉一个通配符

转载 作者:太空狗 更新时间:2023-10-29 17:56:17 33 4
gpt4 key购买 nike

我有一些由点分隔的单词的字符串。示例:

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

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

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

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

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

最佳答案

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

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

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

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

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

关于Python:去掉一个通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18533636/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com