user1947085
user1947085

Reputation: 177

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?

Upvotes: 2

Views: 2734

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

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']

Upvotes: 6

Soulfire
Soulfire

Reputation: 161

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.

Upvotes: 0

Amine Hajyoussef
Amine Hajyoussef

Reputation: 4430

Python 2.6 and newer Python 2.x versions:

line = ['00', '11"', 'aa', 'bb', "cc'"] 
line = [x.translate(None,'\'\"') for x in line]

Upvotes: 1

Related Questions