Remove Part of String Before the Last Forward Slash

后端 未结 6 1965
终归单人心
终归单人心 2021-02-05 19:04

The program I am currently working on retrieves URLs from a website and puts them into a list. What I want to get is the last section of the URL.

So, if the first elemen

6条回答
  •  时光说笑
    2021-02-05 19:40

    Have a look at str.rsplit.

    >>> s = 'https://docs.python.org/3.4/tutorial/interpreter.html'
    >>> s.rsplit('/',1)
    ['https://docs.python.org/3.4/tutorial', 'interpreter.html']
    >>> s.rsplit('/',1)[1]
    'interpreter.html'
    

    And to use RegEx

    >>> re.search(r'(.*)/(.*)',s).group(2)
    'interpreter.html'
    

    Then match the 2nd group which lies between the last / and the end of String. This is a greedy usage of the greedy technique in RegEx.

    Regular expression visualization

    Debuggex Demo

    Small Note - The problem with link.rpartition('//')[-1] in your code is that you are trying to match // and not /. So remove the extra / as in link.rpartition('/')[-1].

提交回复
热议问题