python使用单引号,用单引号分隔Python字符串

本文介绍如何使用Python的正则表达式(re模块)从复杂字符串中提取特定模式的数据,如'Adult'、'classification'等,并探讨了如何处理包含转义引号的场景。通过实例演示了pyparsing库在处理复杂字符串格式上的优势。
摘要由CSDN通过智能技术生成

如果没有未列出的约束,则可以使用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']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值