Convert single-quoted string to double-quoted string
Asked Answered
T

8

38

I want to check whether the given string is single- or double-quoted. If it is single quote I want to convert it to be double quote, else it has to be same double quote.

Thyrse answered 15/12, 2009 at 12:6 Comment(2)
I'm not convinced everyone is interpreting your question the way you intended. Do these strings contain these single and double quotes as part of the content? The best way to explain your question would be to include some examples of what input you have, how you'd like the output to appear, etc. If at all possible, copy and paste from an actual Python console session so there will be no way we can mistake what you mean.Lahdidah
black formatter will do that automatically for you (unless there's a good reason not to).Extravascular
R
26

There is no difference between "single quoted" and "double quoted" strings in Python: both are parsed internally to string objects.

I mean:

a = "European Swallow"
b = 'African Swallow'

Are internally string objects.

However you might mean to add an extra quote inside an string object, so that the content itself show up quoted when printed/exported?

c = "'Unladen Swallow'"

If you have a mix of quotes inside a string like:

a = """ Merry "Christmas"! Happy 'new year'! """

Then you can use the "replace" method to convert then all into one type:

a = a.replace('"', "'") 

If you happen to have nested strings, then replace first the existing quotes to escaped quotes, and later the otuer quotes:

a = """This is an example: "containing 'nested' strings" """
a = a.replace("'", "\\\'")
a = a.replace('"', "'")
Rhine answered 15/12, 2009 at 12:10 Comment(5)
thank you first Actually am getting the the single quote string,double quoted strings dynamically and also am using urljoin(dublequote,singlequote) so here i facing problem the output is combination both but i need it as singleThyrse
When using json, it makes a LOT of difference between a string in ' ' and " ".Influential
json.dumps('dog') ouputs '"dog"' to the file but I want "dog". How to do that?Influential
json.dumps create a Python string - if you are viewing it on the interactive mode, you will see the extra quotes around "dog" -, but if yu write that to a file (or use json.dump directly, a single layer of quotation is used. If you need zero quotes, you shoul strip them manually after json serialization.Rhine
@Rhine yes, but json.loads('dog') will complain about single quotes as it's expecting double quoted strings (which is also defined in rfc7159).Lallation
M
24

Sounds like you are working with JSON. I would just make sure it is always a double quoted like this:

doubleQString = "{0}".format('my normal string')
with open('sampledict.json','w') as f:
    json.dump(doubleQString ,f)

Notice I'm using dump, not dumps.

Sampledict.json will look like this:

"my normal string"
Melisent answered 6/6, 2017 at 8:2 Comment(2)
This is a great answer, and json.dumps will return the string if you'd rather not have to export to a file.Enviable
The double quotes are the output of json.dump/dumps - regardless of the .format call. The first line in your snippet is a no-operation: Python strings are Python strings, regardless of the surrouding quotes used when typing the literal. (And the default representation of strings uses single-quotes - " ' " )Rhine
D
6

In my case I needed to print list in json format. This worked for me:

f'''"inputs" : {str(vec).replace("'", '"')},\n'''

Output:

"inputs" : ["Input_Vector0_0_0", "Input_Vector0_0_1"],

Before without replace:

f'"inputs" : {vec},\n'

"inputs" : ['Input_Vector0_0_0', 'Input_Vector0_0_1'],
Doughty answered 21/4, 2019 at 12:38 Comment(0)
C
5

The difference is only on input. They are the same.

s = "hi"
t = 'hi'
s == t

True

You can even do:

"hi" == 'hi'

True

Providing both methods is useful because you can for example have your string contain either ' or " directly without escaping.

Coussoule answered 15/12, 2009 at 12:9 Comment(2)
Likewise, there is also no difference between the regularly-quoted string ("foo") and triple-quoted string ("""foo""").Hyehyena
@Brain json.dumps('dog') ouputs '"dog"' to the file but I want "dog". How to do that?Influential
C
4

In Python, there is no difference between strings that are single or double quoted, so I don't know why you would want to do this. However, if you actually mean single quote characters inside a string, then to replace them with double quotes, you would do this: mystring.replace('\'', '"')

Cavite answered 15/12, 2009 at 12:11 Comment(3)
I like string.replace("'", '"') slightly better—it has a nice alternating pattern of quotes in it :-).Puffin
thank u so much thank you first Actually am getting the the single quote string,double quoted strings dynamically and also am using urljoin(dublequote,singlequote) so here i facing problem the output is combination both ... Thank u very muchThyrse
Thanks for answering the question instead of going into great detail about how python interprets quotes. I had a use case where a file needed its double quotes replaced with single quotes so that it could be passed into another language that was sensitive to the quote type.Sanskritic
C
1

Actually, none of the answers above as far as I know answers the question, the question how to convert a single quoted string to a double quoted one, regardless if for python is interchangeable one can be using Python to autogenerate code where is not.

One example can be trying to generate a SQL statement where which quotes are used can be very important, and furthermore a simple replace between double quote and single quote may not be so simple (i.e., you may have double quotes enclosed in single quotes).

print('INSERT INTO xx.xx VALUES' + str(tuple(['a',"b'c",'dfg'])) +';')

Which returns:

INSERT INTO xx.xx VALUES('a', "b'c", 'dfg');

At the moment I do not have a clear answer for this particular question but I thought worth pointing out in case someone knows. (Will come back if I figure it out though)

Capsular answered 26/11, 2021 at 17:56 Comment(0)
S
0

If you're talking about converting quotes inside a string, One thing you could do is replace single quotes with double quotes in the resulting string and use that. Something like this:

def toDouble(stmt):
    return stmt.replace("'",'"')
Someday answered 1/11, 2022 at 18:35 Comment(0)
P
0

If you're here because you have have a dict object that you converted to a string using str() and would like the dictionary back, doing json.loads(str_stuffs.replace("'", '"')) should help. So for example,

import json

stuffs = {"stuff1": "value", "stuff2": "value", "stuff3": "value"}
str_stuffs = str(stuffs)

original_stuffs = json.loads(str_stuffs.replace("'", '"'))

Hope this helps!

Putnam answered 10/7 at 11:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.