Search code examples
pythonjsonpython-3.xf-string

unable to add the variable value into a query using f string in python


I am having a JSON script and I want to add a variable value into it using f-string in python but I was unable to do it.

name = "harsha"
query = """mutation {
                createUsers(input:{
                user_name: f"{name}"
                  })
                  {
                    users{
                      user_name
                    }
                  }
              }
        """

enter image description here when i am printing query i am getting the same value not the change value harsha


Solution

  • Everything within the triple quotes is interpreted as being part of the string, not as code. Move the f in front of the triple quotes to have it be interpreted as an f-string.

    This will require escaping the rest of the braces, so you'll end up with this.

    name = "harsha"
    query = f"""mutation {{
                    createUsers(input:{{
                    user_name: {name}
                      }})
                      {{
                        users{{
                          user_name
                        }}
                      }}
                  }}
            """