Search code examples
pythonpython-3.xstringstring-formatting

String Formatting using f-strings in Pythonic way


I'm new to python and learning strings formatting. I'm formatting this string using f-strings, I do this using %s but I want to do this with f-strings.

query = f'''
            summary {
                operation(
                    input: {
                        operation_type: accounts,
                        user_id: {user_id},
                        user_secret: {user_secret},
                        code: {user_id}
                    }
                ) {
                    user_accounts,
                    user_account_type
                }
            }'''

Solution

  • Since {} are used to escape variable names, you need to double them to represent actual curly braces:

    query = f'''
                summary {{
                    operation(
                        input: {{
                            operation_type: accounts,
                            user_id: {user_id},
                            user_secret: {user_secret},
                            code: {user_id}
                        }}
                    ) {{
                        user_accounts,
                        user_account_type
                    }}
                }}'''