Convert single-quoted string to double-quoted string

后端 未结 5 1829
无人及你
无人及你 2020-12-25 12:32

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.

相关标签:
5条回答
  • 2020-12-25 13:01

    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"
    
    0 讨论(0)
  • 2020-12-25 13:09

    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'],
    
    0 讨论(0)
  • 2020-12-25 13:13

    There is no difference between "single quoted" and "double quoted" strigns 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'" 
    

    ?

    Ah - given the clarifciation (posted as a commetn by Kumar, bellow):

    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('"', "'")
    
    0 讨论(0)
  • 2020-12-25 13:19

    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('\'', '"')

    0 讨论(0)
  • 2020-12-25 13:20

    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.

    0 讨论(0)
提交回复
热议问题