【问题标题】:Python: strip a wildcard wordPython:去除通配符
【发布时间】:2013-09-03 05:25:51
【问题描述】:

我有用点分隔的单词的字符串。 示例:

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只是一个例子)

【问题讨论】:

    标签: python regex string wildcard


    【解决方案1】:

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

    【讨论】:

    • 谢谢!对于您的“顺便说一句”:是否有可能仅剥离以正确方式订购的“abcd”?还是仅适用于正则表达式?
    • @aldorado,'abcddcbaabcd'.replace('abcd', '', 1)1 表示只替换一次。
    • @aldorado,我添加了另一个代码,显示了str.replace 的示例用法。
    猜你喜欢
    • 2015-05-10
    • 2012-05-29
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多