How do I find the string between two special characters?

一个人想着一个人 提交于 2019-11-28 12:04:16

Regular expressions are the most flexible option.

For another approach, you can try string's partition and rpartition methods:

>>> s = "[virus 1 [isolated from china]]"
>>> s.partition('[')[-1].rpartition(']')[0]
'virus 1 [isolated from china]'

You can use a greedy regex:

re.search(r'\[(.*)\]', your_string).group(1)

Given your sample input, it looks like every line begins and ends with brackets. In which case, forget regexps, this is trivial:

for line in whatever:
    contents = line.strip()[1:-1]

(I've added the strip in case your line source is leaving the newlines in, or there are invisible spaces after the closing bracket in your input. If it's not necessary, leave it out.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!