我有以下代码:

url = 'abcdc.com'
print(url.strip('.com'))

我以为是abcdc

我得到:abcd

现在我知道了

url.rsplit('.com', 1)

有没有更好的办法?


参见.strip/.rstrip/。lstrip字符串方法在Python中工作?对于第一次尝试的具体解释。


当前回答

如果你需要剥离字符串的某一端,如果它存在,否则什么都不做。我最好的解决方案。您可能会想使用前两个实现中的一个,但是为了完整性,我已经包括了第三个实现。

对于常量后缀:

def remove_suffix(v, s):
    return v[:-len(s)] if v.endswith(s) else v
remove_suffix("abc.com", ".com") == 'abc'
remove_suffix("abc", ".com") == 'abc'

对于正则表达式:

def remove_suffix_compile(suffix_pattern):
    r = re.compile(f"(.*?)({suffix_pattern})?$")
    return lambda v: r.match(v)[1]
remove_domain = remove_suffix_compile(r"\.[a-zA-Z0-9]{3,}")
remove_domain("abc.com") == "abc"
remove_domain("sub.abc.net") == "sub.abc"
remove_domain("abc.") == "abc."
remove_domain("abc") == "abc"

对于常量后缀的集合,对于大量调用的渐近最快的方法:

def remove_suffix_preprocess(*suffixes):
    suffixes = set(suffixes)
    try:
        suffixes.remove('')
    except KeyError:
        pass

    def helper(suffixes, pos):
        if len(suffixes) == 1:
            suf = suffixes[0]
            l = -len(suf)
            ls = slice(0, l)
            return lambda v: v[ls] if v.endswith(suf) else v
        si = iter(suffixes)
        ml = len(next(si))
        exact = False
        for suf in si:
            l = len(suf)
            if -l == pos:
                exact = True
            else:
                ml = min(len(suf), ml)
        ml = -ml
        suffix_dict = {}
        for suf in suffixes:
            sub = suf[ml:pos]
            if sub in suffix_dict:
                suffix_dict[sub].append(suf)
            else:
                suffix_dict[sub] = [suf]
        if exact:
            del suffix_dict['']
            for key in suffix_dict:
                suffix_dict[key] = helper([s[:pos] for s in suffix_dict[key]], None)
            return lambda v: suffix_dict.get(v[ml:pos], lambda v: v)(v[:pos])
        else:
            for key in suffix_dict:
                suffix_dict[key] = helper(suffix_dict[key], ml)
            return lambda v: suffix_dict.get(v[ml:pos], lambda v: v)(v)
    return helper(tuple(suffixes), None)
domain_remove = remove_suffix_preprocess(".com", ".net", ".edu", ".uk", '.tv', '.co.uk', '.org.uk')

最后一个在pypy中可能比在cpython中快得多。对于几乎所有不涉及大量潜在后缀字典的情况(至少在cPython中无法轻松表示为regex), regex变体可能比这个更快。

在PyPy中,regex变体对于大量调用或长字符串几乎肯定更慢,即使re模块使用DFA编译regex引擎,因为lambda的绝大多数开销将由JIT优化。

然而,在cPython中,在几乎所有情况下,你为正则表达式运行的c代码的比较几乎肯定超过了后缀集合版本的算法优势。

编辑:https://m.xkcd.com/859/

其他回答

def strip_end(text, suffix):
    if suffix and text.endswith(suffix):
        return text[:-len(suffix)]
    return text

这里,我有一个最简单的代码。

url=url.split(".")[0]

假设你想删除域名,不管它是什么(.com, .net等)。我建议找到。并从那一刻起移除一切。

url = 'abcdc.com'
dot_index = url.rfind('.')
url = url[:dot_index]

在这里,我使用rfind来解决像abcdc.com这样的url的问题,它应该被简化为abcdc.com的名称。

如果你也关心www.s,你应该明确地检查它们:

if url.startswith("www."):
   url = url.replace("www.","", 1)

replace中的1用于奇怪的边例,例如www.net.www.com

如果你的url比这更乱,看看人们用正则表达式回答的问题。

对于url(通过给定的例子,它似乎是主题的一部分),可以这样做:

import os
url = 'http://www.stackoverflow.com'
name,ext = os.path.splitext(url)
print (name, ext)

#Or:
ext = '.'+url.split('.')[-1]
name = url[:-len(ext)]
print (name, ext)

两者都会输出: (“http://www.stackoverflow”,“。com”)

这也可以与str.endswith(后缀)相结合,如果你只需要分割“。com”,或任何特定的东西。

这取决于你对url的了解程度以及你想要做什么。如果你知道它总是以“。com”(或“。net”或“。org”)结尾,那么

 url=url[:-4]

是最快的解决办法。如果它是一个更通用的url,那么你可能会更好地查看python附带的urlparse库。

另一方面,如果你只是想在期末考试后删除所有内容。'在一个字符串中

url.rsplit('.',1)[0]

将工作。或者如果你想把所有的东西都放在第一。那就试试

url.split('.',1)[0]