意外删除“_" [英] strip remove '_' unexpectedly

查看:32
本文介绍了意外删除“_"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>x = 'abc_cde_fgh'>>>x.strip('abc_cde')'fgh'

_fgh 是预期的.

如何理解这个结果?

解决方案

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

这个例子很好地展示了它:

x.strip('ab_ch')'de_fg'

由于字符a"、b"、c"、h"和_"在remove case中,所以前导的abc_c"都被删除了.其他字符不会被删除.

如果您想删除前导或尾随,我建议使用restartswith/endswith.

def rstrip_word(str, word):如果 str.endswith(word):返回 str[:-len(word)]返回字符串def lstrip_word(str, word):如果 str.startswith(word):返回 str[len(word):]返回字符串def strip_word(str, word):返回 rstrip_word(lstrip_word(str, word), word)

删除多个单词

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

def rstrip_word(str, *words):逐字逐句:如果 str.endswith(word):返回 str[:-len(word)]返回字符串def lstrip_word(str, *words):逐字逐句:如果 str.startswith(word):返回 str[len(word):]返回字符串def strip_word(str, *words):返回 rstrip_word(lstrip_word(str, *words), *words)

请注意这个算法是贪心,它会找到第一个可能的例子然后返回:它可能不会像你期望的那样运行.找到最大长度匹配(虽然不太棘手)有点复杂.

<预><代码>>>>strip_word(x, "abc", "adc_")'_cde_fgh'

>>> x = 'abc_cde_fgh'
>>> x.strip('abc_cde')
'fgh'

_fgh is expected.

How to understard this result?

解决方案

Strip removes any characters it finds from either end from the substring: it doesn't remove a trailing or leading word.

This example demonstrates it nicely:

x.strip('ab_ch')
'de_fg'

Since the characters "a", "b", "c", "h", and "_" are in the remove case, the leading "abc_c" are all removed. The other characters are not removed.

If you would like to remove a leading or trailing word, I would recommend using re or startswith/endswith.

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)

Removing Multiple Words

A very simple implementation (a greedy one) to remove multiple words from a string can be done as follows:

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)

Please note this algorithm is greedy, it will find the first possible example and then return: it may not behave as you expect. Finding the maximum length match (although not too tricky) is a bit more involved.

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

这篇关于意外删除“_"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆