Home > Back-end >  How to make variable inserted strings inside strings use double quote instead of single quote?
How to make variable inserted strings inside strings use double quote instead of single quote?

Time:09-02

In Python, when inserting a list(string) into another string using format(), the inserted string by default uses single quotes:

arr = ["foo"]
print(f"Ahhh I need double quotes here: {arr}")

Ahhh I need double quotes here: ['foo']

How can I output this without having Regex spaghetti?

Ahhh I need double quotes here: ["foo"]

CodePudding user response:

If you can have an intermediate step this could work:

arr = ["foo"]
arr = str(arr).replace("'",'"')
print(f'Ahhh I need double quotes here: {arr}')
  

Output:

Ahhh I need double quotes here: ["foo"]

CodePudding user response:

Do something like this:

arr = "[\"foo\"]"
print(f"Ahhh I need double quotes here: {arr}")

if your want the square bracket inside the formatted string. Notice that quote symbol (' " ') will be interpreted as the end of string, therefore, you need to use the escape character ('\') in order to be able to use the quote inside a string.

CodePudding user response:

The easiest way to do this is using the json library. For example:

import json

arr = ["foo", "it's", 'multiple words with "extra quotes"']
print(f'Ahhh I need double quotes here: {json.dumps(arr)}')

This will print:

Ahhh I need double quotes here: ["foo", "it's", "multiple words with \"extra quotes\""]

Note that the above example handles single quotes fine, but double quotes include an escape character. This is part of the JSON standard.

If you need something more complicated with detailed control, you should create a custom class.

class MyStr:
    def __init__(self, value):
        self._val = value

    def __repr__(self):
        # The return value here is the formatted string
        return f"\"{self._val}\""

Then you can do something like

arr = ["foo"]
arr_mystr = [MyStr(x) for x in arr]
print(f"Ahhh I need double quotes here: {arr_mystr}")

which gives:

Ahhh I need double quotes here: ["foo"]
  • Related