Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python not perform type conversion when concatenating strings?

In Python, the following code produces an error:

a = 'abc' b = 1 print(a + b) 

(The error is "TypeError: cannot concatenate 'str' and 'int' objects").

Why does the Python interpreter not automatically try using the str() function when it encounters concatenation of these types?

like image 619
Symmetric Avatar asked Jun 17 '11 01:06

Symmetric


People also ask

Can strings be concatenated in Python?

Two strings can be concatenated in Python by simply using the '+' operator between them. More than two strings can be concatenated using '+' operator.

Can only concatenate str not type to STR?

The Python "TypeError: can only concatenate str (not "list") to str" occurs when we try to concatenate a string and a list. To solve the error, access the list at a specific index to concatenate two strings, or use the append() method to add an item to the list.

Can Python can concatenate combine words strings and numbers integers?

Python supports string concatenation using + operator. In most of the programming languages, if we concatenate a string with an integer or any other primitive data types, the language takes care of converting them to string and then concatenate it.

Can you concatenate different types in Python?

str. format() is one of the string formatting methods in Python, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting.


2 Answers

The problem is that the conversion is ambiguous, because + means both string concatenation and numeric addition. The following question would be equally valid:

Why does the Python interpreter not automatically try using the int() function when it encounters addition of these types?

This is exactly the loose-typing problem that unfortunately afflicts Javascript.

like image 73
Greg Hewgill Avatar answered Oct 13 '22 08:10

Greg Hewgill


There's a very large degree of ambiguity with such operations. Suppose that case instead:

a = '4' b = 1 print(a + b) 

It's not clear if a should be coerced to an integer (resulting in 5), or if b should be coerced to a string (resulting in '41'). Since type juggling rules are transitive, passing a numeric string to a function expecting numbers could get you in trouble, especially since almost all arithmetic operators have overloaded operations for strings too.

For instance, in Javascript, to make sure you deal with integers and not strings, a common practice is to multiply a variable by one; in Python, the multiplication operator repeats strings, so '41' * 1 is a no-op. It's probably better to just ask the developer to clarify.

like image 25
zneak Avatar answered Oct 13 '22 09:10

zneak