N
N
Nastya Meow2015-12-22 14:27:57
Python
Nastya Meow, 2015-12-22 14:27:57

How to properly format strings from a dictionary?

learning python and according to the book of Lutz
task:
e75d9bf262d046e89d31d9a5d2d4f546.png
outcome:
04ab55909b4743878765eaa3f5c5f5e6.png
tell me, please

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Anton Fedoryan, 2015-12-22
@miymiy

reply = """
Greetings...
Hello %(name)s
Your age squared is %(age)s
"""
values = {'name': 'Bob', 'age': 40}
print(reply % values)

A
Alexander, 2015-12-22
@bIbI4k0

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})

E
e2-e4, 2015-12-22
@e2-e4

values ​​= {'name': 'Bob', 'age':40}
reply = ''
print (reply % values)

D
Dmitry, 2015-12-22
@EvilsInterrupt

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.

I
Ilya Pavlov, 2015-12-24
@Spirkaa

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 question

Ask a Question

731 491 924 answers to any question