2011-03-06 20 views

回答

8

您可以使用regular expression,例如:

import re 

s = "http://example.com/variable/controller/id32434242423423234?param1=321&param2=4324342" 

m = re.search(r'controller/id(\d+)\?',s) 
if m:  
    print "Found the id:", m.group(1) 

如果您需要的值是數字而不是字符串,則可以使用int(m.group(1))。還有很多其他方法可能會更合適,這取決於代碼的更大目標,但沒有更多上下文,這很難說。

+0

作品像一個魅力,thx很多 – Mladen 2011-03-06 13:23:49

+1

雖然它不是必須的如果是,請在帶正則表達式的字符串前加'r',以避免出現像''[\ f]'這樣的問題'(注意'list('\ f')'和'list(r'\ f 「)')。 – jfs 2011-03-08 20:46:14

+0

@ J.F。塞巴斯蒂安:謝謝你的建議 - 我已經做出了改變。 (優秀的用戶名,BTW :)) – 2011-03-08 21:04:24

2
>>> s 
'http://example.com/variable/controller/id32434242423423234?param1=321&param2=4324342' 
>>> s.split("id") 
['http://example.com/variable/controller/', '32434242423423234?param1=321&param2=4324342'] 
>>> s.split("id")[-1].split("?")[0] 
'32434242423423234' 
>>> 
3
>>> import urlparse 
>>> res=urlparse.urlparse("http://example.com/variable/controller/id32434242423423234?param1=321&param2=4324342") 
>>> res.path 
'/variable/controller/id32434242423423234' 
>>> import posixpath 
>>> posixpath.split(res.path) 
('/variable/controller', 'id32434242423423234') 
>>> directory,filename=posixpath.split(res.path) 
>>> filename[2:] 
'32434242423423234' 

使用urlparseposixpath可能是太多針對這種情況,但我認爲這是乾淨的方式來做到這一點。

+0

在Windows上'os.path.split()'不能像你期望的那樣工作。改用'posixpath.split()'。 – jfs 2011-03-08 20:38:52

+0

這很有趣;我在Windows XP上使用Python 2.6.5。什麼版本的Windows不起作用? – 2011-03-08 21:14:58

+0

Windows上的'os.path.split()'使用兩個分隔符r'\ /'並在參數上調用'splitdrive()' - 你不需要這個,只需使用'posixpath.split()'。 – jfs 2011-03-11 16:15:49

0

雖然正則表達式是要走的路,簡單的事情我寫了string parser。在某種程度上,使用PEP 3101進行字符串格式化操作的(未完成)反向操作。這非常方便,因爲這意味着您不必學習指定字符串的另一種方式。

例如:

>>> 'The answer is {:d}'.format(42) 
The answer is 42 

分析器則正好相反:

>>> Parser('The answer is {:d}')('The answer is 42') 
42 

對於你的情況,如果你想要一個int輸出

>>> url = 'http://example.com/variable/controller/id32434242423423234?param1=321&param2=4324342' 
>>> fmt = 'http://example.com/variable/controller/id{:d}?param1=321&param2=4324342' 
>>> Parser(fmt)(url) 
32434242423423234 

如果你想要一個字符串:

>>> fmt = 'http://example.com/variable/controller/id{:s}?param1=321&param2=4324342' 
>>> Parser(fmt)(url) 
32434242423423234 

如果你希望獲得更多的東西在一個字典:

>>> fmt = 'http://example.com/variable/controller/id{id:s}?param1={param1:s}&param2={param2:s}' 
>>> Parser(fmt)(url) 
{'id': '32434242423423234', 'param1': '321', 'param2': '4324342'} 

或元組:

如果你希望獲得更多的東西在一個字典:

>>> fmt = 'http://example.com/variable/controller/id{:s}?param1={:s}&param2={:s}' 
>>> Parser(fmt)(url) 
('32434242423423234', '321', '4324342') 

給它是一個嘗試,它承載here