4

了解使用 str.join 运算符是在 python 中连接字符串的“选择”方式,我在该类型的啄序操作中徘徊:

 "%s %s" % (first_name, last_name)

会适合。它们比使用更快还是更慢+

4

2 回答 2

6

让我们来看看:

>>> first_name = 'Test'
>>> last_name = 'Name'

>>> %timeit "%s %s" % (first_name, last_name)
10000000 loops, best of 3: 168 ns per loop

>>> %timeit ' '.join((first_name, last_name))
10000000 loops, best of 3: 157 ns per loop

>>> %timeit first_name + ' ' + last_name
10000000 loops, best of 3: 103 ns per loop

如果你缓存元组:

>>> name_tuple = (first_name, last_name)

>>> %timeit "%s %s" % name_tuple
10000000 loops, best of 3: 125 ns per loop

>>> %timeit ' '.join(name_tuple)
10000000 loops, best of 3: 114 ns per loop
于 2013-02-28T04:21:44.290 回答
5

回答:没有。

在此处输入图像描述

In [1]: tup = 'hello', 'world'

In [2]: timeit 'hello' + 'world'
10000000 loops, best of 3: 20.2 ns per loop

In [3]: timeit tup[0] + tup[1]
10000000 loops, best of 3: 129 ns per loop

In [4]: timeit '{}{}'.format('hello', 'world')
1000000 loops, best of 3: 285 ns per loop

In [5]: timeit '{}{}'.format(*tup)
1000000 loops, best of 3: 281 ns per loop

In [6]: timeit '%s%s' % ('hello', 'world')
10000000 loops, best of 3: 122 ns per loop

In [7]: timeit '%s%s' % tup
10000000 loops, best of 3: 135 ns per loop

In [8]: timeit ''.join(['hello', 'world'])
1000000 loops, best of 3: 210 ns per loop

In [9]: timeit ''.join(tup)
10000000 loops, best of 3: 121 ns per loop
于 2013-02-28T04:23:36.233 回答