首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >remove_prefix和remove_suffix函数

remove_prefix和remove_suffix函数
EN

Code Review用户
提问于 2013-11-05 03:16:55
回答 1查看 3.2K关注 0票数 0

如果前缀/后缀与字符串的开头或结尾不匹配,那么根据我如何调用这些函数,它们应该引发异常,或者返回未修改的原始文本。

我现在在一个简单的脚本中使用这些函数,所以没有必要使这些成员函数成为某个类的成员函数。我希望找到一种方法来简化逻辑,将任何公共代码提取到私有函数(S)中,改进代码风格(尽管我认为有几种不同的标准)。

代码语言:javascript
复制
def remove_prefix(text, prefix, raise_if_no_match=True):
    exc_msg = 'Text "{}" does not start with a prefix "{}".'.format(text, prefix)
    if not prefix or not text:
        if not raise_if_no_match:
            return text
        if len(prefix) == len(text):
            return ''
        raise ValueError(exc_msg)
    if text.startswith(prefix):
        return text[len(prefix):]
    if raise_if_no_match:
        raise ValueError(exc_msg)
    return text

def remove_suffix(text, suffix, raise_if_no_match=True):
    exc_msg = 'Text "{}" does not end with a suffix "{}".'.format(text, suffix)
    if not suffix or not text:
        if not raise_if_no_match:
            return text
        if len(suffix) == len(text):
            return ''
        raise ValueError(exc_msg)
    if text.endswith(suffix):
        return text[:-len(suffix):]
    if raise_if_no_match:
        raise ValueError(exc_msg)
    return text

print remove_prefix('Hello, World', 'Hello, ')
# ValueError: Text "Hello, World" does not start with a prefix "Hello, Hello".
#print remove_prefix('Hello, World', 'Hello, Hello')
print remove_prefix('Hello, World', 'Hello, Hello', raise_if_no_match=False)

print remove_suffix('I am singing in the rain', ' in the rain')
# ValueError: Text "I am singing in the rain" does not end with a suffix "swinging in the rain".
#print remove_suffix('I am singing in the rain', 'swinging in the rain')
print remove_suffix('I am singing in the rain', 'swinging in the rain', raise_if_no_match=False)

输出:

世界你好,世界我在歌唱我在雨中歌唱

EN

回答 1

Code Review用户

回答已采纳

发布于 2013-11-05 11:30:41

首先,我要说的是,把你的打印声明变成一个测试。这样,您就可以有信心地改变实现,相信您没有破坏任何东西。

下面是这些调试打印作为测试的内容:

代码语言:javascript
复制
class TestRemove(unittest.TestCase):

    def test_remove_prefix(self):
        hello = 'Hello, World'
        value = remove_prefix(hello, 'Hello, ')
        self.assertEqual(value, 'World')
        value = remove_prefix(hello, 'Hello, Hello', raise_if_no_match=False)
        self.assertEqual(value, hello)
        self.assertRaises(ValueError, remove_prefix, hello, 'Hello, Hello')

    def test_remove_suffix(self):
        singing = 'I am singing in the rain'
        value = remove_suffix(singing, ' in the rain')
        self.assertEqual(value, 'I am singing')
        value = remove_suffix(singing, 'swinging in the rain', raise_if_no_match=False)
        self.assertEqual(value, singing)
        self.assertRaises(ValueError, remove_suffix, singing, 'swinging in the rain')

我认为您应该使用内置的字符串操作,可以找到这里。即startswith()endswith()spilt()rsplit()

您还可以重新分配变量名,以便在函数中提供更清晰的流。这是我的remove_prefix()版本。

代码语言:javascript
复制
def remove_prefix(text, prefix, raise_if_no_match=True):
    if (text.startswith(prefix)):
        text = text.split(prefix, 1)[1]
    else:
        if (raise_if_no_match):
            msg_fmt = 'Text "{}" does not end with a prefix "{}".'
            raise ValueError(msg_fmt.format(text, prefix))
    return text

由此,我相信你可以改变remove_suffix()

此外,我还会向函数中添加docstring,以便记录引发的参数和异常。

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/33817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档