开发者

Inconsistency of Python plus operator

开发者 https://www.devze.com 2023-04-08 18:01 出处:网络
In [26]: l=[] In [27]: s=\"asdsad\" In [28]: l+=s In [29]: l Out[29]: [\'a\', \'s\', \'d\', \'s\', \'a\', \'d\']
In [26]: l=[]

In [27]: s="asdsad"

In [28]: l+=s

In [29]: l
Out[29]: ['a', 's', 'd', 's', 'a', 'd']

However,

In [30]: l+s
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/xiaohan/code/proteincrawler/id_crawler.py in <module>()
----> 1 
      2 
      3 
      4 
      5 

TypeError: can only concatenate list (not "str") to list

So, the + operators in '+=' and '+' are different.

But I think they should be the same, because they are all plus

Am I wrong or something happens behind the scene开发者_运维技巧?


This is explained here. Copied from the link:

It's because the += operator is doing the equivalent of calling the extend method, which treats its argument as a generic sequence, and doesn't enforce type.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号