Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Triple Double Quote String format

I'm getting the following error, how should I fix it?

KeyError: 'a' Process finished with exit code 1

s = """
a b c {a}
""".format({'a':'123'})

print s
like image 651
user1187968 Avatar asked Dec 23 '22 14:12

user1187968


2 Answers

You need to pass in the arguments by name .format(a=123) or use format_map which expects a dictionary:

s = """
a b c {a}
""".format_map({'a':'123'})
like image 90
MSeifert Avatar answered Jan 08 '23 20:01

MSeifert


Named formatting variables must be passed by name:

>>> s = """
... a b c {a}
... """.format(a=123)
>>> print(s)

a b c 123

If you're providing a dict of data, you can "unpack" the names:

>>> d = {'a': 123}
>>> s = """
... a b c {a}
... """.format(**d)
>>> print(s)

a b c 123
like image 23
wim Avatar answered Jan 08 '23 21:01

wim