首页 文章

如何从Python中删除字符串末尾的子字符串?

提问于
浏览
272

我有以下代码:

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

我期待: abcdc

我得到了: abcd

现在我做

url.rsplit('.com', 1)

有没有更好的办法?

16 回答

  • 8

    strip 并不代表"remove this substring" . x.strip(y)y 视为一组字符,并从 x 的末尾剥离该集合中的任何字符 .

    相反,您可以使用 endswith 并切片:

    url = 'abcdc.com'
    if url.endswith('.com'):
        url = url[:-4]
    

    或使用正则表达式:

    import re
    url = 'abcdc.com'
    url = re.sub('\.com$', '', url)
    
  • 0

    如果你确定字符串只出现在最后,那么最简单的方法是使用'replace':

    url = 'abcdc.com'
    print url.replace('.com','')
    
  • 6
    def strip_end(text, suffix):
        if not text.endswith(suffix):
            return text
        return text[:len(text)-len(suffix)]
    
  • 1

    因为似乎没有人指出这个问题:

    url = "www.example.com"
    new_url = url[:url.rfind(".")]
    

    这应该比使用 split() 的方法更有效,因为没有创建新的列表对象,并且此解决方案适用于具有多个点的字符串 .

  • 56

    取决于你对你的网址的了解以及你正在尝试做什么 . 如果您知道它将始终以'.com'(或'.net'或'.org')结尾

    url=url[:-4]
    

    是最快的解决方案 . 如果它是一个更通用的URL,那么你可能更好地查看python附带的urlparse库 .

    另一方面,如果你想在最终''之后删除所有内容 . 然后在一个字符串中

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

    将工作 . 或者,如果你只想要一切都达到第一个' . '然后试试

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

    在一行中:

    text if not text.endswith(suffix) or len(suffix) == 0 else text[:-len(suffix)]
    
  • 30

    url[:-4] 怎么样?

  • 411

    如果你知道这是一个扩展,那么

    url = 'abcdc.com'
    ...
    url.rsplit('.', 1)[0]  # split at '.', starting from the right, maximum 1 split
    

    这与 abcdc.comwww.abcdc.comabcdc.[anything] 同样适用,并且更具可扩展性 .

  • 0

    对于网址(因为它似乎是给定示例的主题的一部分),可以做这样的事情:

    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')

    如果您只需要拆分".com"或任何特定的内容,也可以将其与 str.endswith(suffix) 结合使用 .

  • 0

    url.rsplit(' . com',1)

    是不对的 .

    你真正需要写的是

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

    ,它看起来很简洁恕我直言 .

    但是,我个人的偏好是这个选项,因为它只使用一个参数:

    url.rpartition('.com')[0]
    
  • 0
    import re
    
    def rm_suffix(url = 'abcdc.com', suffix='\.com'):
        return(re.sub(suffix+'$', '', url))
    

    我想重复这个答案作为最有表现力的方式来做到这一点 . 当然,以下将占用更少的CPU时间

    def rm_dotcom(url = 'abcdc.com'):
        return(url[:-4] if url.endswith('.com') else url)
    

    但是,如果CPU是瓶颈,为什么要用Python编写?

    什么时候CPU是瓶颈?在司机,也许 .

    使用正则表达式的优点是代码可重用性 . 如果你接下来要删除只有三个字符的'.me'怎么办?

    相同的代码可以解决问题 .

    >>> rm_sub('abcdc.me','.me')
    'abcdc'
    
  • 0

    这是正则表达式的完美用法:

    >>> import re
    >>> re.match(r"(.*)\.com", "hello.com").group(1)
    'hello'
    
  • 20

    或者您可以使用拆分:

    a = 'abccomputer.com'
    res = a.split('.com',1)[0]
    
  • 36
    def remove_file_type(infile):
    import re
    return(re.sub('\.[^.]*$','',infile))
    remove_file_type('abc.efg')'abc'
    
  • 2

    在我的情况下,我需要提出异常,所以我做了:

    class UnableToStripEnd(Exception):
        """A Exception type to indicate that the suffix cannot be removed from the text."""
    
        @staticmethod
        def get_exception(text, suffix):
            return UnableToStripEnd("Could not find suffix ({0}) on text: {1}."
                                    .format(suffix, text))
    
    
    def strip_end(text, suffix):
        """Removes the end of a string. Otherwise fails."""
        if not text.endswith(suffix):
            raise UnableToStripEnd.get_exception(text, suffix)
        return text[:len(text)-len(suffix)]
    
  • 9

    如果你的意思是只剥离扩展名

    url = 'abcdc.com'
    print('.'.join(url.split('.')[:-1]))
    

    它适用于任何扩展,其他潜在的点也存在于文件名中 . 它只是将字符串拆分为点上的列表并在没有最后一个元素的情况下连接它 .

    可能不是最快的,但对我来说它比其他方法更具可读性 .

相关问题