The string join method can concatenate strings significantly faster than using the '+' operator. I think Raymond Hettinger talked about this in one of his presentations archived on pyvideo.org.
width = 1000
def foo(width):
horizontal_line = '{'
for i in range(width):
horizontal_line += (' ' + '#ffffff')
horizontal_line += '}'
%timeit foo(width)
1000 loops, best of 3: 210 µs per loop
def foo(width):
horizontal_line = (
'{' +
' '.join(
'#ffffff' for i in range(width)
) +
'}'
)
%timeit foo(width)
10000 loops, best of 3: 129 µs per loop
def foo(width):
horizontal_line = ''.join([
'{',
' '.join(
'#ffffff' for i in range(width)
),
'}',
])
%timeit foo(width)
10000 loops, best of 3: 129 µs per loop