mjoy
mjoy

Reputation: 680

How to replace the double quotation marks around a string in python list?

I have a dataframe column with some of them containing single quotation mark in the string like so (which are two single quotation marks next to each other so it can escape the single quotation in SQL):

 'Group1>>TV>>Blue>>Q''19>>four'

and the rest have strings that don't contain a quotation mark. When converting my dataframe column to get a list of all strings that I can copy and paste into an SQL query, it ends up putting double quotation marks around the string when I need a single quotation mark for SQL.

 ids = ["Group1>>TV>>Blue>>Q''19>>four", 'Group3>>Desktop>>Blue>>>two', 'Group1>>Desktop>>Green>>>two']

I want to change it so that I get this:

ids = ['Group1>>TV>>Blue>>Q''19>>four', 'Group3>>Desktop>>Blue>>>two', 'Group1>>Desktop>>Green>>>two']

I have tried a few different things but nothing seems to work.

 [str(x) for x in ids]
 [x.strip('"') for x in ids]
 [x.replace('"', "'") for x in ids]

Upvotes: 0

Views: 976

Answers (1)

yatu
yatu

Reputation: 88236

One approach adapting this answer would be to extend python's built-in str class modifying the canonical string representation of the object, i.e. the __repr__() dunder method so that the double quotes are replaced by single quotes:

class str2(str):
    def __repr__(self):
        return ''.join(('\'', super().__repr__()[1:-1], '\''))

Then simply instanciate with the strings in you list:

ids = ["Group1>>TV>>Blue>>Q''19>>four", 'Group3>>Desktop>>Blue>>>two', \
       'Group1>>Desktop>>Green>>>two']

list(map(str2, ids))

['Group1>>TV>>Blue>>Q''19>>four',
 'Group3>>Desktop>>Blue>>>two',
 'Group1>>Desktop>>Green>>>two']

Upvotes: 3

Related Questions