4

I am trying to print variables and strings in a line. like [Hello! name How are you?] -> [Hello! John How are you?]

json file

#json01.json
{
"greet" : ["Hello! *name* How are you?"] # I don't know how to write this part..
}

and this is where I am..

import json

a = 'greet'
name = 'John'

with open('json01.json') as json_file:
json_dict = json.load(json_file)

if a in json_dict:
    print(json_dict[a]) # I don't know how to write this part as well.. 

How should I do to get the result I want?

Sorry for the poor explanation and Thank you!

2
  • What is the error in this? Commented Apr 16, 2020 at 5:25
  • @HarshaBiyani it's not a request for debugging, the question is how to make the output string have the name inserted in the right place. The existing code ignores that completely. Commented Apr 16, 2020 at 5:35

2 Answers 2

5

There are various ways to format strings in python.

Here are 3 examples:

"Hello! %s How are you?" % name
"Hello! %(name)s How are you?" % locals()
"Hello! {name} How are you?".format(name=name)

Search the web for "python string formatting", and you'll find plenty of useful stuff.

Sign up to request clarification or add additional context in comments.

5 Comments

does it work when it's decoded from json to dictionary?
Sure, json_dict[a] is an expression returning a string
How you get the dictionary doesn't matter. What matters is that you pull a string out of the dictionary (like with json_dict[a], like you already have) that has the right "template" stuff in it (you make this happen by editing the .json file to match), and then you use the matching code to replace the place-holder with the desired name value.
@shx2 - I don't catch the difference between suggested approaches and f-strings. Could give me a clue? Isn't "Hello! {name} How are you?".format(name=name) equivalent of f"Hello! {name} How are you?"?
@kajakIYD, as the answer is phrased, there is no difference. However, the 3 examples apply to the question because you can replace ""Hello! ..." with json_dict[a]. I don't think you can use such an expression in conjunction with f-strings (because the template is not fixed and known at runtime).
0

In case you want to "substitute" more than only one variable into string, with pointing out explicitly what do you want to instantiate without typing many arguments in .format():

  1. Create a dictionary. Keys should be strings to be replaced in acquired string and values should be variables that will appear in place of keys.
  2. Use double asterisk ** to extract keys from namespace dictionary to "unpack" dictionary into .format() arguments list to substitute keys by values in acquired string

According to your example:

import json

a = 'greet'
name = 'John'
weight = 80
height = 190
age = 23
# 1.
namespace = {'name': name, 'age': age, 'weight': weight, 'height': height}

json_dict_all_keys = json.loads('{"greet" : "Hello! {name}, {age} years old, {height}cm, {weight}kg. How are you?"}')
json_dict_some_keys = json.loads('{"greet" : "Hello! {name}, {weight}kg. How are you?"}') 
json_dict_mixed_keys = json.loads('{"greet" : "Hello! {name}, {other} years old, {key}cm, {weight}kg. How are you?"}')
json_dict_none_of_keys = json.loads('{"greet" : "Hello! {some}, {other} years old, {key}cm, {here}kg. How are you?"}')

if a in json_dict:
    # 2.
    print(json_dict_all_keys[a].format(**namespace))  # Hello! John, 23 years old, 190cm, 80kg. How are you?
    print(json_dict_some_keys[a].format(**namespace))  # Hello! John, 80kg. How are you?
    print(json_dict_mixed_keys[a].format(**namespace))  # Raising KeyError!
    print(json_dict_none_of_keys[a].format(**namespace))  # Raising KeyError too!

As you can see, there is no requirement to use all of "keys" from namespace. But be careful - when in string you want to format appears "key" that is not included in namespace KeyError will occur.

To simplify explaination I used json.loads instead of loading json from file with json.load.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.