Home > OS >  How do I place variables inside of a triple-quoted string literal?
How do I place variables inside of a triple-quoted string literal?

Time:02-11

data = """
{
  "sender": "I want a variable here",
  "memo": "and here another variable",
  "amount": another variable here 
}
"""

I've tried using f in front of the string, and several other methods, but this is keeping me hung up.

CodePudding user response:

Don't construct JSON strings by hand as there are many intricacies of the JSON spec and your method is prone to errors. Instead, construct a dictionary first:

my_dict = {
    "sender": my_sender_variable,
    "memo": my_memo_variable,
    "amount": my_amount_variable
    }

then use the json module to convert it to a string:

my_json = json.dumps(my_dict, indent=4)
  • Related