简体   繁体   中英

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?

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.

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.

The short answer would be because Python is a strongly typed language.

This was a design decision made by Guido. It could have been one way or another really, concatenating str and int to str or int .

The best explanation, is still the one given by guido, you can check it here

The other answers have provided pretty good explanations, but have failed to mention that this feature is known a Strong Typing. Languages that perform implicit conversions are Weakly Typed.

Because Python does not perform type conversion when concatenating strings. This behavior is by design, and you should get in the habit of performing explicit type conversions when you need to coerce objects into strings or numbers.

Change your code to:

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

And you'll see the desired result.

Python would have to know what's in the string to do it correctly. There's an ambiguous case: what should '5' + 5 generate? A number or a string? That should certainly throw an error. Now to determine whether that situation holds, python would have to examine the string to tell. Should it do that every time you try to concatenate or add two things? Better to just let the programmer convert the string explicitly.

More generally, implicit conversions like that are just plain confusing! They're hard to predict, hard to read, and hard to debug.

tell python that the int is a list to disambiguate the '+' operation.

['foo', 'bar'] + [5]

this returns: ['foo', 'bar', 5]

That's just how they decided to design the language. Probably the rationale is that requiring explicit conversions to string reduces the likelihood of unintended behavior (eg integer addition if both operands happen to be ints instead of strings).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM