我想将只有一个号码转换为字符串。我应该选择哪种方法?在这种情况下哪种方法更快?什么转换为str方法更快?
num = 10
str_num = str(num) # or
str_num = "%d" % num # or
str_num = "{}".format(num)
我想将只有一个号码转换为字符串。我应该选择哪种方法?在这种情况下哪种方法更快?什么转换为str方法更快?
num = 10
str_num = str(num) # or
str_num = "%d" % num # or
str_num = "{}".format(num)
它甚至很重要吗?正如Donald Knuth曾经说的不成熟的优化是编程中所有邪恶(或至少大部分)的根源。
在实用性和代码可读性的基础上区分它们,而不是速度。
# When you just need to cast an object into a string
str_num = str(num)
# Use the other two when you are substituting integers
# (or any other compatible object) in a string. Example -
"My name is {0} and my age is {1}".format('hpandher', 25)
@Chris_Rands已经对它进行了更新,但我仍然认为这是一个有效的问题。 – hspandher
如果你转换只有一个号码,任何方法可以简单地通过它需要键入它的时间限制,所以无论你使用首先想到的。
您使用的方法之间的比较。考虑到输出,不管你用哪种方法只转换一个数字。
In [100]: %time str(num)
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 9.3 µs
Out[100]: '10'
In [101]: %time "%d" % num
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 8.58 µs
Out[101]: '10'
In [102]: %time "{}".format(num)
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 14.1 µs
Out[102]: '10'
你的'int'有多大?除非它绝对是巨大的,那么其他人所说的并不是真正的问题,尽管 –