如果没有未列出的约束,则可以使用regex执行类似的操作:>>> s = "'Adult' 'Adverse Drug Reaction Reporting Systems/*classification' '*Drug-Related Side Effects and Adverse Reactions' 'Hospital Bed Capacity 300 to 499' 'Hospitals County' 'Humans' 'Indiana' 'Pharmacy Service Hospital/*statistics & numerical data'"
>>> import re
>>> regex = re.compile(r"'[^']*'")
>>> regex.findall(s)
["'Adult'", "'Adverse Drug Reaction Reporting Systems/*classification'", "'*Drug-Related Side Effects and Adverse Reactions'", "'Hospital Bed Capacity 300 to 499'", "'Hospitals County'", "'Humans'", "'Indiana'", "'Pharmacy Service Hospital/*statistics & numerical data'"]
我的regex将'留在字符串中,您可以用str.strip("'")轻松地删除它们。在
^{pr2}$
注意,这只是因为我假设字符串中没有转义引号。。。e、 g.你从来没有:
'foo\'bar'在许多编程情况下,是表示字符串的一种完全有效的方法。如果确实存在这种情况,则需要使用更健壮的解析器,例如pyparsing:>>> import pyparsing as pp
>>> [x[0][0].strip("'") for x in pp.sglQuotedString.scanString(s)]
['Adult', 'Adverse Drug Reaction Reporting Systems/*classification', '*Drug-Related Side Effects and Adverse Reactions', 'Hospital Bed Capacity 300 to 499', 'Hospitals County', 'Humans', 'Indiana', 'Pharmacy Service Hospital/*statistics & numerical data']
>>> s2 = r"'foo\'bar' 'baz'"
>>> [x[0][0].strip("'") for x in pp.sglQuotedString.scanString(s2)]
["foo\\'bar", 'baz']