Issue
I have one variable val = "O'brien" and I want to create a following string using this variable. -->
s1 = "{\"id1\":\"O'brien\"}"
I tried with this:
s1 = "{\"id1\":\"'{}'.format(x)\"}"
However, It's giving me literal values as
'{"id1":"\'{}\'.format(x)"}'
What I want instead is
s1 = "{\"id1\":\"O'brien\"}"
So that, I can make it dictionary using
json.loads(s1)
Which will give me this output:
{'id1': "O'brien"}.
I tried with many ways but couldn't get it, please suggest some good ways
Solution
There are multiple ways you can format your string, but this is how I would do it using an f string;
val = "O'brien"
s1 = f"{{\"id1\":\"{val}\"}}"
s1 is then equal to
{"id1":"O'Brien"}
If you want to use .format(x)
it needs to be outside the outermost quote and you need to escape the outermost curly brackets
s1 = "{{\"id1\":\"{}\"}}".format(val)
Answered By - Brandon Kauffman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.