了解使用str.join运算符是在python中连接字符串的“选择”方式,我在类型的啄食顺序操作中徘徊:
"%s %s" % (first_name, last_name)
适合。它们比使用+
更快还是更慢?
答案 0 :(得分: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
答案 1 :(得分: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