Python 字符串形式的列表长度
是否有一种首选(不难看)的方式将列表长度输出为字符串?目前我正在像这样嵌套函数调用:
print "Length: %s" % str(len(self.listOfThings))
这似乎是一个黑客解决方案,是否有更优雅的方式来实现相同的结果?
Is there a preferred (not ugly) way of outputting a list length as a string? Currently I am nesting function calls like so:
print "Length: %s" % str(len(self.listOfThings))
This seems like a hack solution, is there a more graceful way of achieving the same result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要调用
str
:请注意,使用
%
已被弃用,如果您需要,您应该更喜欢使用str.format
使用 Python 2.6 或更高版本:You don't need the call to
str
:Note that using
%
is being deprecated, and you should prefer to usestr.format
if you are using Python 2.6 or newer:"Length: %d" % len(self.listOfThings)
应该效果很好。字符串格式化的要点是将数据转换为字符串,因此调用
str
并不是您想要的:提供数据本身,在本例中为int
。int
可以采用多种方式进行格式化,最常见的是%d
,它提供了它的十进制表示形式(我们习惯于查看数字的方式)。对于任意的东西,你可以使用%s
,它在所表示的对象上调用str
;永远不需要自己调用str
。我还会考虑
"Length: %d" % (len(self.listOfThings),)
——有些人习惯性地使用元组作为str.__mod__
的参数,因为这样的方式它的工作原理有点有趣,他们希望提供更一致的东西。如果我特别使用
print
,我可能只使用print "Length:", len(self.listOfThings)
。不过,我实际上很少使用print
。"Length: %d" % len(self.listOfThings)
should work great.The point of string formatting is to make your data into a string, so calling
str
is not what you want: provide the data itself, in this case anint
. Anint
can be formatted many ways, the most common being%d
, which provides a decimal representation of it (the way we're used to looking at numbers). For arbitrary stuff you can use%s
, which callsstr
on the object being represented; callingstr
yourself should never be necessary.I would also consider
"Length: %d" % (len(self.listOfThings),)
—some people habitually use tuples as the argument tostr.__mod__
because the way it works is sort of funny and they want to provide something more consistent.If I was using
print
in particular, I might just useprint "Length:", len(self.listOfThings)
. I seldom actually useprint
, though.好吧,您可以省略
str()
调用,但仅此而已。为什么调用函数是“黑客”?Well, you can leave out the
str()
call, but that's about it. How come is calling functions "a hack"?