0
我有一個網址如下:的Python添加到URL
http://www.example.com/boards/results/current:entry1,current:entry2/modular/table/alltables/alltables/alltables/2011-01-01
我需要插入在這種情況下,節點 '我們',具體如下:
http://www.example.com/boards/results/us/current:entry1,current:entry2/modular/table/alltables/alltables/alltables/2011-01-01
使用Python的裏urlparse圖書館,我可以走的路徑如下:
path = urlparse(url).path
...然後使用一個複雜和醜陋的例程涉及到基於斜槓的路徑分裂並插入新的節點,然後重新構建URL
>>> path = urlparse(url).path
>>> path.split('/')
['', 'boards', 'results', 'current:entry1,current:entry2', 'modular', 'table', 'alltables', 'alltables', 'alltables', '2011-01-01']
>>> ps = path.split('/')
>>> ps.insert(4, 'us')
>>> '/'.join(ps)
'/boards/results/current:entry1,current:entry2/us/modular/table/alltables/alltables/alltables/2011-01-01'
>>>
是否有更優雅/ pythonic的方式來完成此使用默認庫?
編輯: URL中的'結果'不是固定的 - 它可以是'結果'或'產品'或'價格'等等。然而,它會永遠在'董事會'之後。
'url.replace('results /','results/us /')'? –