Python 拆卸板条'_';意外地

Python 拆卸板条'_';意外地,python,strip,Python,Strip,\u fgh是预期的 如何理解这个结果?Strip从子字符串的任意一端删除它找到的任何字符:它不会删除尾随或前导字 这个例子很好地说明了这一点: >>> x = 'abc_cde_fgh' >>> x.strip('abc_cde') 'fgh' 由于字符“a”、“b”、“c”、“h”和“u”在remove case中,因此前导的“abc_uc”都被删除。其他字符不会被删除 如果要删除前导或尾随的单词,我建议使用re或startswith/endswith

\u fgh
是预期的


如何理解这个结果?

Strip从子字符串的任意一端删除它找到的任何字符:它不会删除尾随或前导字

这个例子很好地说明了这一点:

>>> x = 'abc_cde_fgh'
>>> x.strip('abc_cde')
'fgh'
由于字符“a”、“b”、“c”、“h”和“u”在remove case中,因此前导的“abc_uc”都被删除。其他字符不会被删除

如果要删除前导或尾随的单词,我建议使用
re
startswith/endswith

x.strip('ab_ch')
'de_fg'
删除多个单词

从字符串中删除多个单词的一个非常简单的实现(贪婪的实现)可以如下所示:

def rstrip_word(str, word):
    if str.endswith(word):
        return str[:-len(word)]
    return str

def lstrip_word(str, word):
    if str.startswith(word):
        return str[len(word):]
    return str

def strip_word(str, word):
    return rstrip_word(lstrip_word(str, word), word)
请注意,这个算法是贪婪的,它会找到第一个可能的例子,然后返回:它可能不会像您期望的那样运行。查找最大长度匹配(虽然不太复杂)有点复杂

def rstrip_word(str, *words):
    for word in words:
        if str.endswith(word):
            return str[:-len(word)]
    return str

def lstrip_word(str, *words):
    for word in words:
        if str.startswith(word):
            return str[len(word):]
    return str

def strip_word(str, *words):
    return rstrip_word(lstrip_word(str, *words), *words)

在strip方法的文档中,“chars参数是一个指定要删除的字符集的字符串”。这就是为什么除“fgh”之外的所有字符都会被删除(包括两个下划线)。

strip()删除字符,而不是子字符串。例如:

>>> strip_word(x, "abc", "adc_")
'_cde_fgh'

我误解了脱衣舞的意思。我试着剥去一个
单词
,这不是剥去的功能。thx.@DylanSu,在这种情况下,我包含了剥离单个单词的实现。如果需要,使用arg列表可以将其扩展到一般情况。
x.strip('abcde_')
'fgh'