1

有人可以帮我从字符串中删除字符,只留下'[....]'中的字符吗?

For example:

a  = newyork_74[mylocation]

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

c = [mylocation]
4

2 回答 2

1

像这样的东西:

>>> import re
>>> strs = "newyork_74[mylocation]"
>>> re.sub(r'(.*)?(\[)','\g<2>',strs)
'[mylocation]'
于 2013-06-22T19:49:54.757 回答
0

Assuming no nested structures, one way would be using itertools.dropwhile,

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

Another would be to use regexs,

>>> import re
>>> pat = re.compile(r'\[.*\]')
>>> b = pat.search(a).group(0)
>>> b
'[mylocation]'
于 2013-06-22T19:45:52.893 回答