0

I am trying to get an output similar to this.

{
  "Continent": "Asia",
  "Country": "Japan" 
} 

The code below is throwing an error.

    var = "Japan"
message_body_3 = '{\n  \"Continent\": \"Asia\",\n  \"Country\": \"{0}\" \n} '.format(var)

Error:

    message_body_3 = '{\n  \"Continent\": \"Asia\",\n  \"Country\": \" {0} \" \n} '.format(var)
KeyError: '\n  "Continent"'

I want the {0} to be replaced with my variable.

What's the best way to achieve the result. I need to have backslashes and quotes in my string. Is there any way to do this in python ?

chexxmex
  • 117
  • 1
  • 8
  • 2
    Does this answer your question? [How can I print literal curly-brace characters in a string and also use .format on it?](https://stackoverflow.com/questions/5466451/how-can-i-print-literal-curly-brace-characters-in-a-string-and-also-use-format) – Hampus Larsson Aug 20 '21 at 22:34
  • 1
    "I tried f strings but they don't support backslashes.". Show what you did with all error tracebacks or it never happened – Mad Physicist Aug 20 '21 at 22:34
  • @MadPhysicist `f'{"hello\n"}'` results in: `SyntaxError: f-string expression part cannot include a backslash`. – Hampus Larsson Aug 20 '21 at 22:36
  • message_body_3 = '{{\n \"Continent\": \"Asia\",\n \"Country\": \"{0}\" \n}} '.format("Japan") print(message_body_3) – Waseem Randhawa Aug 20 '21 at 22:50
  • You should use `pprint` and a dictionary, not manually putting in newline characters to a string – OneCricketeer Aug 20 '21 at 23:03
  • @WaseemRandhawa How do I write, if I have one more layer in the string: message_body_3 = '{{\n \"Continent\": \"Asia\",\n \"Country\": \" {0} \" \n \"Address\" : { \n \"State\": \" {1} \" \n \"City\": \" {2} \" \n }\n}}'.format(var1,var2,var3). – chexxmex Aug 20 '21 at 23:04
  • https://stackoverflow.com/questions/3229419/how-to-pretty-print-nested-dictionaries – OneCricketeer Aug 20 '21 at 23:09
  • message_body_3 = '{{\n \"Continent\": \"Asia\",\n \"Country\": \"{0}\", \n \"Continent\": \"Asia\"}} '.format("Japan") print(message_body_3) – Waseem Randhawa Aug 20 '21 at 23:14
  • message_body_3 = '{{\n \"Continent\": \"Asia\",\n \"Country\": \" {0} \" \n \"Address\" :{{\n\"State\": \" {1} \" \n \"City\": \" {2} \"\n}} \n}}'.format('var1','var2','var3') print(message_body_3) – Waseem Randhawa Aug 20 '21 at 23:23
  • You can use `{{` for literal braces, or do `'{' + f'...' + '}\n'` – Mad Physicist Aug 21 '21 at 00:12
  • The error is because you need to tell the f-string that `{` is literal, not a replacement in that case. Hence the duplicate. – Mad Physicist Aug 21 '21 at 00:13

0 Answers0