09 April 2018

python string concatenation is a bad practice

i think because python is a scripting language, people tend to thing it's super fine to do something like this:

>>> val + '-string'

the problem is that the + operator does not do any casting of the variable to make it compatible with the string. this sort of thing will throw an error if the type of val is anything other than a string.

check it:

>>> val = None
>>> val + '-string'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    val + '-string'
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>>> '{}-string'.format(val)
'None-string'

>>> val = 4
>>> val + '-string'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    val + '-string'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> '{}-string'.format(val)
'4-string'

now, you could force cast it using str(val), but that seems silly when you can just use the format() method on the string object to handle things for you.