简体   繁体   English

Python列表长度为字符串

[英]Python List length as a string

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? 这似乎是一个黑客解决方案,是否有更优雅的方式来实现相同的结果?

You don't need the call to str : 你不需要调用str

print "Length: %s" % len(self.listOfThings)

Note that using % is being deprecated, and you should prefer to use str.format if you are using Python 2.6 or newer: 请注意,不推荐使用% ,如果您使用的是Python 2.6或更高版本,则应该更喜欢使用str.format

print "Length: {0}".format(len(self.listOfThings))  

"Length: %d" % len(self.listOfThings) should work great. "Length: %d" % len(self.listOfThings)应该很好用。

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 an int . 字符串格式化的目的是使您的数据成为一个字符串,因此调用str不是您想要的:提供数据本身,在本例中为int An int 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). int可以通过多种方式进行格式化,最常见的是%d ,它提供了它的十进制表示(我们习惯于查看数字的方式)。 For arbitrary stuff you can use %s , which calls str on the object being represented; 对于任意的东西,你可以使用%s ,它在被表示的对象上调用str ; calling str yourself should never be necessary. 调用str自己不应该是必要的。

I would also consider "Length: %d" % (len(self.listOfThings),) —some people habitually use tuples as the argument to str.__mod__ because the way it works is sort of funny and they want to provide something more consistent. 我也会考虑"Length: %d" % (len(self.listOfThings),) - "Length: %d" % (len(self.listOfThings),)人习惯性地使用元组作为str.__mod__的参数,因为它的工作方式很有趣,他们希望提供更一致的东西。

If I was using print in particular, I might just use print "Length:", len(self.listOfThings) . 如果我特别使用print ,我可能只使用print "Length:", len(self.listOfThings) I seldom actually use print , though. 不过,我很少使用print

Well, you can leave out the str() call, but that's about it. 好吧,你可以省略str()调用,但这就是它。 How come is calling functions "a hack"? 为什么称功能为“黑客”?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM