Remove the last part of string separated with dot in Python

前端 未结 2 1012
既然无缘
既然无缘 2021-01-12 18:07

How is it possible to convert in elegant way strings like:

\'test.test1.test2\'
\'test.test3.test4\'

into strings like these:



        
相关标签:
2条回答
  • 2021-01-12 18:20

    No need for regular expressions here.

    Use str.rsplit():

    output = inputstr.rsplit('.', 1)[0]
    

    or str.rpartition():

    output = inputstr.rpartition('.')[0]
    

    str.rpartition() is the faster of the two but you need Python 2.5 or newer for it.

    Demo:

    >>> 'test.test1.test2'.rsplit('.', 1)[0]
    'test.test1'
    >>> 'test.test1.test2'.rpartition('.')[0]
    'test.test1'
    >>> 'test.test3.test4'.rsplit('.', 1)[0]
    'test.test3'
    >>> 'test.test3.test4'.rpartition('.')[0]
    'test.test3'
    

    And a time comparison against a million runs:

    >>> from timeit import timeit
    >>> timeit("s.rsplit('.', 1)[0]", "s = 'test.test1.test2'")
    0.5848979949951172
    >>> timeit("s.rpartition('.')[0]", "s = 'test.test1.test2'")
    0.27417516708374023
    

    where you can run 2 million str.rpartition() calls for the price of 1 million str.rsplit()'s.

    0 讨论(0)
  • 2021-01-12 18:41

    Use rsplit to split from the end, limit to 1 split:

    your_string.rsplit('.', 1)
    
    0 讨论(0)
提交回复
热议问题