Using + with strings considered bad
Peter Otten
__peter__ at web.de
Wed Apr 29 05:24:51 EDT 2015
Cecil Westerhof wrote:
> Because I try to keep my lines (well) below 80 characters, I use the
> following:
> print('Calculating fibonacci and fibonacci_memoize once for ' +
> str(large_fibonacci) + ' to determine speed increase')
>
> But I was told that using + with strings was bad practice. Is this
> true?
No. What was meant was probably that str.join() is preferred when you are to
concat an arbitrary number of strings, i. e.
# wrong
s = ""
for item in items:
s += " " + item.name # may be inefficient depending on implementation
s = s[1:]
# correct
s = " ".join(item.name for item in items)
(For more complex operations than just getting an attribute you may have to
write a helper generator:
def bogus(items):
prev = ""
for item in items:
yield str(len(prev) - len(item))
prev = item
s = "*".join(bogus(items))
)
> If so, what is the better way to do this?
Python concats adjacent string constants implicitly
>>> "one" "two"
'onetwo'
but in CPython an extra + will be removed by the peephole optimiser:
>>> def f(): return "one" + "two"
...
>>> import dis
>>> dis.dis(f)
1 0 LOAD_CONST 3 ('onetwo')
3 RETURN_VALUE
> print('Calculating fibonacci and fibonacci_memoize once for ' +
> str(large_fibonacci) + ' to determine speed increase')
You could write that as
print('Calculating fibonacci and fibonacci_memoize once for '
'{} to determine speed increase'.format(large_fibonacci))
but in a simple case like yours I'd go with the obvious
print(
'Calculating fibonacci and fibonacci_memoize once for',
large_fibonacci,
'to determine speed increase')
More information about the Python-list
mailing list