我想在两个字符之间找到一个单词,但结束字符可以是两个不同的。 *) 或 |
我想要的文本是“特殊文本”(该文本行可以不同)
字符串可以如下所示: 大量文字(特殊文字|更多文字) 但是也 很多文字(特殊文字)
line = "a lot of text (*special text |more text*)"
substring = line[line.index('*')+1:line.index('|')]
print(substring)
您应该使用
正则表达式,而不是使用
index
。例如,您可以搜索 (*
和 *)
之间的文本,然后将其拆分为 |
。请注意,*
、(
和)
是正则表达式中的特殊字符,需要转义。
>>> import re
>>> line = "a lot of text (*special text |more text*) bla (*even more | special | text*)"
>>> re.findall(r"\(\*(.*?)\*\)", line)
['special text |more text', 'even more | special | text']
>>>: [y for x in re.findall(r"\(\*(.*?)\*\)", line) for y in x.split("|")]
['special text ', 'more text', 'even more ', ' special ', ' text']