[英]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 KeyError:'a'过程以退出代码1结束
s = """
a b c {a}
""".format({'a':'123'})
print s
You need to pass in the arguments by name .format(a=123)
or use format_map
which expects a dictionary: 您需要通过名称
.format(a=123)
传递参数或使用需要字典的format_map
:
s = """
a b c {a}
""".format_map({'a':'123'})
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
You are using the format
method for strings incorrectly. 您正在使用
format
方法错误地使用字符串。 format
requires that you pass in keyword arguments when you want to substitute names inside a string. format
要求您在要在字符串中替换名称时传入关键字参数。
The correct form to use the method in your case would be the following: 在您的情况下使用该方法的正确形式如下:
s = """
a b c {a}
""".format(a='123')
print s
However if you do want to pass in a dictionary, then you can unpack it into keyword arguments by prepending **
before the dictionary itself. 但是,如果您确实希望传入字典,则可以通过在字典本身之前添加
**
来将其解压缩为关键字参数。 This will unpack the dictionary into the the keyword argument of a='123'
like the code above. 这会将字典解压缩到
a='123'
的关键字参数,就像上面的代码一样。
Please read more about Python strings and the string format method here . 请在此处阅读有关Python字符串和字符串格式方法的更多信息 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.