有人可以帮我从字符串中删除字符,只留下'[....]'中的字符吗?
For example:
a = newyork_74[mylocation]
b = # strip the frist characters until you reach the first bracket [
c = [mylocation]
答案 0 :(得分:1)
这样的事情:
>>> import re
>>> strs = "newyork_74[mylocation]"
>>> re.sub(r'(.*)?(\[)','\g<2>',strs)
'[mylocation]'
答案 1 :(得分: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]'