How can I split a url string up into separate parts in Python?

前端 未结 6 981
南笙
南笙 2020-12-13 08:02

I decided that I\'ll learn python tonight :) I know C pretty well (wrote an OS in it) so I\'m not a noob in programming so everything in python seems pretty easy, but I don\

6条回答
  •  无人及你
    2020-12-13 08:42

    If this is the extent of your URL parsing, Python's inbuilt rpartition will do the job:

    >>> URL = "http://example.com/random/folder/path.html"
    >>> Segments = URL.rpartition('/')
    >>> Segments[0]
    'http://example.com/random/folder'
    >>> Segments[2]
    'path.html'
    

    From Pydoc, str.rpartition:

    Splits the string at the last occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself

    What this means is that rpartition does the searching for you, and splits the string at the last (right most) occurrence of the character you specify (in this case / ). It returns a tuple containing:

    (everything to the left of char , the character itself , everything to the right of char)
    

提交回复
热议问题