Answer the question
In order to leave comments, you need to log in
How to properly format strings from a dictionary?
learning python and according to the book of Lutz
task:
outcome:
tell me, please
Answer the question
In order to leave comments, you need to log in
reply = """
Greetings...
Hello %(name)s
Your age squared is %(age)s
"""
values = {'name': 'Bob', 'age': 40}
print(reply % values)
You have python3 and the book uses the latter.
In the third python, print is a function, not a language construct, so you need to write print():
print("hello, %(name)s, you age squared is %(age)s" % {"name": "Bob", "age": 40})
Nastya Meow : The correct answer was given to you by comrade. Alexander !
He said that you are using Python 3, and the author of the book is using Python 2.
The bottom line is that in 2, the print statement is part of the language and is a language construct. And in 3-ke this is not part of the language and not a language construct, but a function. Function syntax has always been with parentheses. The compiler even told you that you have some kind of chaos with "parenthesis" in the 'print' call.
PS:
In the world of Python developers, there are two camps "Lovers 2" and "Lovers 3". At the same time, there is a lot of code written both using 2 and 3. There are also many systems where the perverts wrote part of the system in 2 and part in 3. Therefore, as a future Python programmer, you need to be able to program in both worlds.
Visual instructions for using % and .format():
https://pyformat.info/
reply = """
Greetings...
Hello {name}
Your age squared is {age}
"""
values = {"name": "Bob", "age": 40}
print(reply.format(**values))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question