not*_*ink 5 python formatting python-2.7
所以我对python中的.format机制感到困惑。(我目前使用的是2.7.6)
所以,这显然是有效的:
>>> "hello {test1}".format(**{'test1': 'world'})
'hello world'
Run Code Online (Sandbox Code Playgroud)
也是如此:
>>> "hello {test_1}".format(**{'test_1': 'world'})
'hello world'
Run Code Online (Sandbox Code Playgroud)
但两者都不是:
>>> "hello {test:1}".format(**{'test:1': 'world'})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'test'
Run Code Online (Sandbox Code Playgroud)
也不:
>>> "hello {test.1}".format(**{'test.1': 'world'})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'test'
Run Code Online (Sandbox Code Playgroud)
工作。
但由于某种原因,以下情况会发生:
>>> "hello {test:1}".format(**{'test': 'world'})
'hello world'
Run Code Online (Sandbox Code Playgroud)
因此,被替换的字符串中的变量名称似乎不能包含冒号:或句点.。有什么办法可以逃脱这些角色吗?我希望从字典中替换的字符串偶尔有句点或同时有句点或冒号。
这是因为您可以使用迷你格式语言来访问对象的属性。例如,我在自己的自定义类工作中经常使用它。假设我已经为我需要使用的每台计算机定义了一个类。
class Computer(object):
def __init__(self,IP):
self.IP = IP
Run Code Online (Sandbox Code Playgroud)
现在我想对整个范围的计算机做一些事情
list_comps = [Computer(name,"192.168.1.{}".format(IP)) for IP in range(12)]
for comp in list_comps:
frobnicate(comp) # do something to it
print("Frobnicating the computer located at {comp.IP}".format(comp=comp))
Run Code Online (Sandbox Code Playgroud)
现在它会打印出来
Frobnicating the computer located at 192.168.1.0
Frobnicating the computer located at 192.168.1.1
Frobnicating the computer located at 192.168.1.2 # etc etc
Run Code Online (Sandbox Code Playgroud)
因为每次,它都会找到我传递给格式化程序 () 的对象comp,获取其属性IP,然后使用它。在您的示例中,您为格式化程序提供了一些看起来像属性访问器 ( .) 的内容,因此它尝试访问访问器之前给定的对象,然后查找其定义的属性。
您的最后一个示例之所以有效,是因为它正在寻找test,并且找到了!该符号对于格式化程序来说是特殊的,因为它标志着格式迷你语言的:结束和开始。kwarg例如:
>>> x = 12.34567
>>> print("{x:.2f}".format(x))
12.34
Run Code Online (Sandbox Code Playgroud)
后面.2f的:告诉字符串格式化程序将参数x视为 afloat并在小数点后 2 位数字后截断它。这是有详细记录的,我强烈建议您仔细阅读并添加书签以供将来使用!这很有帮助!
| 归档时间: |
|
| 查看次数: |
1345 次 |
| 最近记录: |