Python Forum
Add variable value to string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Add variable value to string (/thread-27065.html)



Add variable value to string - pythonlearner1 - May-24-2020

I am creating variable

dashboard_id="66862fa0-dafa-4d28572533a"
I want to create a another variable and insert this value to it

Output:
{ "objects":[ { "type":"dashboard", "id":"66862fa0-dafa-4d28572533a" } ] , "includeReferencesDeep": true }
this is how i am creating this but do not know how to replace this id

data = '\n{ "objects":[\n   {\n "type":"dashboard",\n "id":"66862fa0-dafa-4d28572533a"\n } ] ,\n "includeReferencesDeep": true\n}'



RE: Add variable value to string - michael1789 - May-24-2020

Use and F-String.

id = "66862fa0-dafa-4d28572533a"

string = f"some stuff{id}some more stuff"



RE: Add variable value to string - pythonlearner1 - May-24-2020

I did do this and it worked. but now thinking if I can do this in one line

      data1 = '\n{ "objects":[\n   {\n "type":"dashboard",\n "id":'
      data2 = '\n } ] ,\n "includeReferencesDeep": true\n}'
      data = data1 + '"' + dashboard_id + '"' + data2

Michael, that does not work beceasue I have { and ' and \n all in that string. it gives me error


RE: Add variable value to string - buran - May-25-2020

You are creating JSON. Of course one way is to use string manipulation/str methods to do it.
Better way is to use json module
import json

data = {"objects":[],
        "includeReferencesDeep": True}

dashboard_id = "66862fa0-dafa-4d28572533a"
data['objects'].append({'type':'dashboard', 'id':dashboard_id})


json_string = json.dumps(data, indent=4)
print(json_string)
Output:
{ "objects": [ { "type": "dashboard", "id": "66862fa0-dafa-4d28572533a" } ], "includeReferencesDeep": true }
There could be more objects, other objects types, etc. You need to learn to manipulate json.


RE: Add variable value to string - pythonlearner1 - May-25-2020

Thank you Buran, That is what I needed. yes I never thought that I am setting up json. still stuck in old way of doing (bash scripting)


RE: Add variable value to string - ndc85430 - May-25-2020

If you do stuff in shell scripts, do you know about jq? It's a really handy command line tool for doing stuff with JSON.