0

I want these 2 string variables in my other string :

{"prompt":"**String 1**","completion":" **String 2**"}

The problem is I run into a problem because of the multiple quotations.

file_object = open('Sample.txt', 'a')
x = "hello"
y = "hi"
file_object.write('{"prompt":"{}","completion":" {}"}'.format(x,y))

This is what I have tried but It doesn't work.

My intended output : {"prompt":"hello","completion":" hi"}

eshirvana
  • 23,227
  • 3
  • 22
  • 38
  • 2
    Looks like you are trying to write JSON data. Have a look at the [json](https://docs.python.org/3/library/json.html) package (especially `json.dump`) for that. – rauberdaniel Dec 27 '22 at 18:36
  • What is the error? – roganjosh Dec 27 '22 at 18:37
  • 1
    I'm going out on a limb - regardless of whether you'd be better using `json` or not, it's probably that you didn't close the file and flush the contents to disk. I can't see an error in your quotation marks – roganjosh Dec 27 '22 at 18:38
  • 1
    Also, you should just use the `json` package from the stdlib as others have suggested. – Axe319 Dec 27 '22 at 18:40
  • @Axe319 yeah the answer to that problem actually worked, the problem was that I had to use double curly-braces in the begining and in the end : file_object.write('{{"prompt":"{}","completion":" {}"}}'.format(x,y)) – Navid Aslankhani Dec 27 '22 at 18:46
  • `json.dumps({ 'prompt': { } })` is *way* easier than fighting against quoting. – tadman Dec 27 '22 at 18:50

0 Answers0