简体   繁体   English

删除所有用引号引起来的内容或在Python中是数字吗?

[英]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.

相关问题 Python查找用单引号引起来的字符串 - Python find string enclosed in single quotes Python - JSONDecodeError:需要用双引号括起来的属性名称 - Python - JSONDecodeError: Expecting property name enclosed in double quotes Python:JSONDecodeError:期望用双引号括起来的属性名称 - Python: JSONDecodeError: Expecting property name enclosed in double quotes Python/Json:期望用双引号引起来的属性名称 - Python/Json:Expecting property name enclosed in double quotes ValueError:期望在 Python 中用双引号括起来的属性名称 - ValueError: Expecting property name enclosed in double quotes in Python 捕获括号内的所有内容 - 正则表达式 - Capture everything enclosed parentheses - regex 替换所有以数字python开头的内容 - Replace everything that starts with number python 使用 Python 将括号中的数字(字符串)转换为负整数(或浮点数)? - Convert a number enclosed in parentheses (string) to a negative integer (or float) using Python? python-解析编码的json文件-期望属性名称用双引号引起来 - python - parse encoded json file - Expecting property name enclosed in double quotes 用于识别包含在三引号内的有效 Python 字符串的 Javascript 风味正则表达式 - Javascript flavor regex for identifying valid Python strings enclosed within triple quotes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM