Using + with strings considered bad

Andrew Berg aberg010 at my.hennepintech.edu
Wed Apr 29 07:40:47 EDT 2015


On 2015.04.29 04:08, Mark Lawrence wrote:
> On 29/04/2015 09:29, 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? If so, what is the better way to do this?
>>
> 
> It's not bad practice as such, it's simply that performance takes a nose 
> dive if you're contatenating large numbers of strings.  If performance 
> is an issue the recommended way is to write.
> 
> ' '.join(strings)
> 
I thought it was frowned upon because it's less readable for anything non-trivial.

hero1 = 'Batman'
hero2 = 'Robin'
villain = 'The Joker'
place = 'Gotham City'

sentence = hero1 + " and " + hero2 + " fight " + villain + " in " + place + "."
# doesn't flow as well as:
sentence = "{hero1} and {hero2} fight {villain} in {place}.".format(
		hero1=hero1,hero2=hero2,villain=villain,place=place)




More information about the Python-list mailing list