1
有人可以帮我从字符串中去掉字符,只留下“[....]”中的字符吗?从字符串中提取方括号内的文本
For example:
a = newyork_74[mylocation]
b = # strip the frist characters until you reach the first bracket [
c = [mylocation]
有人可以帮我从字符串中去掉字符,只留下“[....]”中的字符吗?从字符串中提取方括号内的文本
For example:
a = newyork_74[mylocation]
b = # strip the frist characters until you reach the first bracket [
c = [mylocation]
假设没有嵌套结构,一种方法是使用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]'
像这样:
>>> import re
>>> strs = "newyork_74[mylocation]"
>>> re.sub(r'(.*)?(\[)','\g<2>',strs)
'[mylocation]'
你有没有尝试过ING? –
'[]是否可以嵌套? – arshajii
这听起来像是[正则表达式]的工作(http://docs.python.org/2/library/re.html)。 – 2013-06-22 19:41:46