让我说我有这个字符串:
myString="'Hello'+yes+'Whats hello'6"
我正在寻找一种方法来删除引号中的所有内容
所以,它会变成:
"+yes+"
因为'Hello'和'Whats hello'用引号括起来。 6是一个数字。
有办法做到这一点吗?也许使用正则表达式?我尝试用For循环做这个,但我猜我的逻辑不是很好。
答案 0 :(得分:6)
Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> re.sub(r"('[^']*'|\d)", "", "'Hello'+yes+'Whats hello'6")
'+yes+'
>>>
(...|...)
匹配一件事或另一件事; '[^']*'
匹配引号内的任何引号; \d
匹配数字。 re.sub(pattern, replacement, string)
用替换替换每个模式实例。
ps注意结果中的'
只是python在字符串周围加上引号! (你可以在python中使用单引号或双引号; python在打印字符串时更喜欢单行,如果字符串本身不包含任何内容)。
更新 - 这就是你想要的吗?
>>> import re
>>> re.sub(r"('[^']*'|(?<![a-zA-Z])\d(?![a-zA-Z]))", "", "'Hello'+yes+'Whats hello'6")
'+yes+'
>>> re.sub(r"('[^']*'|(?<![a-zA-Z])\d(?![a-zA-Z]))", "", "+ye5s")
'+ye5s'