我很困惑Python中的.format机制。(我目前使用的是2.7.6版本)
这个显然可以工作:
>>> "hello {test1}".format(**{'test1': 'world'})
'hello world'
同样适用于:
>>> "hello {test_1}".format(**{'test_1': 'world'})
'hello world'
但是两者都不:
>>> "hello {test:1}".format(**{'test:1': 'world'})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'test'
nor:
>>> "hello {test.1}".format(**{'test.1': 'world'})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'test'
工作。
但由于某些原因,以下内容可以:
>>> "hello {test:1}".format(**{'test': 'world'})
'hello world'
看起来在被替换的字符串中,变量名不能包含冒号:
或句点.
。有没有办法转义这些字符?我想要从字典中替换的字符串偶尔会包含句点、冒号或两者都有。
:
和.
?在使用.format()
之前,我需要以某种方式重新格式化我的文本以将它们删除吗? - not link:
。我的直觉告诉我你不能这样做,但是你可以试一下看看! - Adam Smithprint "你好 {test:20},最近怎么样?".format(**{'test':'世界'})
,你就会知道{test:1}
到底是做什么的了。 - Adam Smith