问题描述
我有一个带有 a
、b
、c
属性的 Python 对象.
我仍然使用旧的字符串格式,所以我通常会手动打印这些:
print '我的对象有字符串 a=%s, b=%s, c=%s' % (obj.a, obj.b, obj.c)
最近,我的字符串变得超长,我更愿意将对象简单地传递给字符串格式函数,例如:
print '我的对象有字符串 a=%a, b=%b, c=%c'.format(obj)
但是,语法不正确.这可能吗?
您可以在格式字段本身内使用 .attribute_name
符号:
print '我的对象有字符串 a={0.a}, b={0.b}, c={0.c}'.format(obj)
以下是演示:
>>>类测试(对象):... def __init__(self, a, b, c):... self.a = a... self.b = b... self.c = c...>>>obj = 测试(1、2、3)>>>'我的对象有字符串 a={0.a}, b={0.b}, c={0.c}'.format(obj)'我的对象有字符串 a=1, b=2, c=3'>>>但是请注意,执行此操作时确实需要对格式字段进行编号.此外,如您所见,str.format
函数的格式字段由大括号 {...}
表示,而不是 %
签名.
有关详细信息,请参阅 Python 中的格式字符串语法的参考.
I have a Python object with attributes a
, b
, c
.
I still use old string formatting, so I'd normally print these manually:
print 'My object has strings a=%s, b=%s, c=%s' % (obj.a, obj.b, obj.c)
Lately, my strings have been getting super long, and I'd much rather be able to simply pass the object into a string format function, something like:
print 'My object has strings a=%a, b=%b, c=%c'.format(obj)
However, the syntax is incorrect. Is this possible?
You can use the .attribute_name
notation inside the format fields themselves:
print 'My object has strings a={0.a}, b={0.b}, c={0.c}'.format(obj)
Below is a demonstration:
>>> class Test(object):
... def __init__(self, a, b, c):
... self.a = a
... self.b = b
... self.c = c
...
>>> obj = Test(1, 2, 3)
>>> 'My object has strings a={0.a}, b={0.b}, c={0.c}'.format(obj)
'My object has strings a=1, b=2, c=3'
>>>
Note however that you do need to number the format fields when doing this. Also, as you can see, the str.format
function has its format fields denoted by curly braces {...}
, not the %
sign.
For more information, here is a reference on the Format String Syntax in Python.
这篇关于使用 str.format() 访问对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!