2013-06-22 74 views
1

有人可以幫我從字符串中去掉字符,只留下「[....]」中的字符嗎?從字符串中提取方括號內的文本

For example: 

a = newyork_74[mylocation] 

b = # strip the frist characters until you reach the first bracket [ 

c = [mylocation] 
+0

你有沒有嘗試過ING? –

+1

'[]是否可以嵌套? – arshajii

+0

這聽起來像是[正則表達式]的工作(http://docs.python.org/2/library/re.html)。 – 2013-06-22 19:41:46

回答

0

假設沒有嵌套結構,一種方法是使用itertools.dropwhile

>>> from itertools import dropwhile 
>>> b = ''.join(dropwhile(lambda c: c != '[', a)) 
>>> b 
'[mylocation]' 

另一個是使用regexs

>>> import re 
>>> pat = re.compile(r'\[.*\]') 
>>> b = pat.search(a).group(0) 
>>> b 
'[mylocation]' 
1

像這樣:

>>> import re 
>>> strs = "newyork_74[mylocation]" 
>>> re.sub(r'(.*)?(\[)','\g<2>',strs) 
'[mylocation]'