简体   繁体   中英

Strip double quotes from single quotes in string

['00', '11"', 'aa', 'bb', "cc'"] 

This is in 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. 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:

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 :

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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM