简体   繁体   English

为什么Python在连接字符串时不执行类型转换?

[英]Why does Python not perform type conversion when concatenating strings?

In Python, the following code produces an error: 在Python中,以下代码会产生错误:

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

(The error is "TypeError: cannot concatenate 'str' and 'int' objects"). (错误是“TypeError:无法连接'str'和'int'对象”)。

Why does the Python interpreter not automatically try using the str() function when it encounters concatenation of these types? 为什么Python解释器在遇到这些类型的串联时不会自动尝试使用str()函数?

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? 为什么Python解释器在遇到这些类型的添加时不会自动尝试使用int()函数?

This is exactly the loose-typing problem that unfortunately afflicts Javascript. 这正是松散打字的问题,不幸的是折磨了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' ). 目前尚不清楚a是否应该被强制转换为整数(导致5 ),或者b是否应该被强制转换为字符串(导致'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; 例如,在Javascript中,为了确保处理整数而不是字符串,通常的做法是将变量乘以1; in Python, the multiplication operator repeats strings, so '41' * 1 is a no-op. 在Python中,乘法运算符重复字符串,因此'41' * 1是无操作。 It's probably better to just ask the developer to clarify. 最好是让开发人员澄清一下。

The short answer would be because Python is a strongly typed language. 简短的回答是因为Python是一种强类型语言。

This was a design decision made by Guido. 这是Guido做出的设计决定。 It could have been one way or another really, concatenating str and int to str or int . 它可能是这样或那样的,将strint连接到strint

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. 因为Python在连接字符串时不执行类型转换。 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. Python必须知道字符串中的内容才能正确执行。 There's an ambiguous case: what should '5' + 5 generate? 有一个模棱两可的案例: '5' + 5应该产生什么? 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. 现在要确定这种情况是否成立,python必须检查要告诉的字符串。 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. 告诉python int是一个消除'+'操作歧义的列表。

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

this returns: ['foo', 'bar', 5] 这会返回:['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). 可能的理由是,要求对字符串进行显式转换会降低意外行为的可能性(例如,如果两个操作数恰好是整数而不是字符串,则为整数加法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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