[英]Strip double quotes from single quotes in string
['00', '11"', 'aa', 'bb', "cc'"]
This is in Python. 这是在Python中。 I want to strip off the double quotes so that my output becomes
我想去除双引号,以便我的输出成为
['00', '11', 'aa', 'bb', 'cc']
How do I do this? 我该怎么做呢?
Looks like you've to use the str.strip()
function two times here. 看起来您必须在这里两次使用
str.strip()
函数。 First to remove the "
and then '
. 首先删除
"
然后是'
。
In [1]: lis=['00', '11"', 'aa', 'bb', "cc'"]
In [2]: [x.strip('"').strip("'") for x in lis]
Out[2]: ['00', '11', 'aa', 'bb', 'cc']
or as suggested by @DSM we don't require 2 strip()
calls: 或@DSM建议,我们不需要2个
strip()
调用:
In [14]: [x.strip("'" '"') for x in lis]
Out[14]: ['00', '11', 'aa', 'bb', 'cc']
because, neighboring string literal are automatically combined : 因为,相邻的字符串文字会自动组合:
In [15]: "'" '"'
Out[15]: '\'"'
In [16]: "a"'b'"c"'d'
Out[16]: 'abcd'
Another alternative can be regex
: 另一个选择可以是
regex
:
In [6]: [re.search(r'\w+',x).group() for x in lis]
Out[6]: ['00', '11', 'aa', 'bb', 'cc']
Python 2.6 and newer Python 2.x versions: Python 2.6和更新的Python 2.x版本:
line = ['00', '11"', 'aa', 'bb', "cc'"]
line = [x.translate(None,'\'\"') for x in line]
You should make use of regular expressions. 您应该使用正则表达式。 Have a look at this site for more information.
请访问此站点以获取更多信息。
http://www.regular-expressions.info/python.html http://www.regular-expressions.info/python.html
Regular expressions are the code version of Find and Replace. 正则表达式是“查找和替换”的代码版本。 What you are looking for is to use a regular expression such as r'[\\'\\"]' and replace it with an empty string. While Python is not my biggest strength, that should give you a push in the right direction.
您正在寻找的是使用正则表达式,例如r'[\\'\\“]'并将其替换为空字符串。虽然Python不是我的最大优点,但应该可以向正确的方向发展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.