pythonpython-3.xstringquotations

What is wrong with my Python syntax: I am trying to use multiple quotation marks plus variables in a string


I am trying to use Python to write to a file. However, the code has multiple " in it plus calls a variable. I simply cannot manage the syntax.

The code should result in:

{
"Name of site": "https://.google.com",

Where the website is a variable not a string.

The code attempt is below. It never resolves the variable and just displays it as a string called host_name. I have attempted to add backslashes and quotations (various types of single and double) but whatever I try does not work.

with open ("new_file.txt", "a") as f:
           f.write ("{ \n")
           
           f.write("\"Name of site\": \"https://" + host_name + ", \n")

The new_file.txt shows:

"Name of site":  "https:// + host_name + "\," + "

I have no idea where the "\," comes from.


Solution

  • You can use f strings, and take advantage of the fact that both '' and "" create string literals.

    >>> host_name = example.com
    >>> output = "{\n"+ f'"Name of site": "https://{host_name}",' + "\n"
    >>> print(output)
    {
    "Name of site": "https://example.com",
    
    
    

    Note that in that example you have to also concatenate strings in order to avoid the fact that f-strings don't allow either braces or backslashes; however, there is even a way around that.

    newline = '\n'
    l_curly = "{"
    output = f'{l_curly}{newline}"Name of site": "https://{host_name}", {newline}'
    

    So that's how you'd build the string directly. But it does also seem more likely that what you really want to is to construct a dictionary, then write that dictionary out using JSON.

    >>> import json
    >>> host_name = 'example.com'
    >>> data = {"Name of site": f"https://{host_name}"}
    >>> output = json.dumps(data, indent=4)
    >>> print(output)
    {
        "Name of site": "https://example.com"
    }