Issue
I am trying to work out how to complete a task that asks the following:
Create a string and use a method to generate a description of the new car as shown below. Print it – it should be formatted like the text below (including the line breaks).
Yesterday I bought a [Make] [Model].
It’s not “too” old. It was made in [year] …
I like it, though. It’s [colour], and it has [doors] doors!
The variables (make, model, year, colour and doors) need to be populated from a dictionary.
I have programmed the dictionary to look like this:
Car = {
'Make': 'Mitsubishi',
'Model': 'Lancer',
'Year': '2002',
'Colour': 'Green',
'Doors': '4',
}
How can i fill the variables in that string of text by referencing the dictionary ‘Car’?
Thank you!
Solution
You can create a template string, and then burst the dictionary values to format it. Example.
fstr = "Yesterday I bought a {} {}.\n\nIt’s not “too” old. It was made in {} …\n\nI like it, though. It’s {}, and it has {} doors!"
Car = {
'Make': 'Mitsubishi',
'Model': 'Lancer',
'Year': '2002',
'Colour': 'Green',
'Doors': '4',
}
print(fstr.format(*Car.values()))
Gives an output like
Yesterday I bought a Mitsubishi Lancer.
It’s not “too” old. It was made in 2002 …
I like it, though. It’s Green, and it has 4 doors!
So, you can apply the format with any dictionary you want.
Condition: You have to make sure the key/values are in the same order of the fillers.
Answered By – Kris
Answer Checked By – Jay B. (BugsFixing Admin)