[英]Deleting everything that is enclosed with quotes or is a number in Python?
Lets say I have this string: 可以说我有这个字符串:
myString="'Hello'+yes+'Whats hello'6"
I am looking for a way to delete everything enclosed in quotes 我正在寻找一种删除引号中所有内容的方法
So, it would become: 因此,它将变为:
"+yes+"
Because, 'Hello' and 'Whats hello' are enclosed by quotes. 因为“ Hello”和“ Whats hello”用引号引起来。 And 6 is a number. 而6是一个数字。
Is there a way to do this? 有没有办法做到这一点? Maybe using Regular Expressions? 也许使用正则表达式? I tried doing this with a For Loop, but I guess my logic wasn't that great. 我尝试使用For循环进行此操作,但我想我的逻辑并不是那么好。
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+'
>>>
(...|...)
matches one thing or another; (...|...)
匹配一件事或另一件事; '[^']*'
matches anything but a quote inside quotes; '[^']*'
除引号内的引号外均匹配; \\d
matches digits. \\d
匹配数字。 re.sub(pattern, replacement, string)
replaces each instance of pattern with the replacement. re.sub(pattern, replacement, string)
用该替换替换每个pattern实例。
ps note that the '
in the result are just python putting quotes around the string! ps注意,结果中的'
只是python在字符串周围加上引号! (you can use single or double quotes in python; python prefers single when printing strings, if the string itself doesn't contain any). (您可以在python中使用单引号或双引号;如果字符串本身不包含任何字符串,则在打印字符串时python首选使用单引号)。
update - is this what you want? 更新 -这是您想要的吗?
>>> 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.