TypeError: coercing to Unicode错误的一个解决办法

2021年7月22日更新:

这个帖子有太多人看过,估计他们都是乘兴而来,败兴而归,因为浏览量大但评论很少😅

为免内疚,特此重写✊

出错原因

导致出现该错的原因有很多,我出错的原因是没有认真仔细地阅读报错信息(里面已经提示这是个TypeError),以及python2自动将字符串紧跟逗号翻译成不完整的tuple的奇葩行为。

复现代码

vi a.py

#encoding=utf-8

s1 = 'a' + 'b',
print s1
s2 = u'甲' + s1 + u'乙'
print s2

触发过程

wanghaipeng@ubuntu:~/projects/test$ python a.py 
('ab',)
Traceback (most recent call last):
  File "a.py", line 5, in <module>
    s2 = u'甲' + s1 + u'乙'
TypeError: coercing to Unicode: need string or buffer, tuple found
 

  • 看复现代码的第3行末尾,字符串'b'不小心跟了个逗号
  • 第4行的打印语句,从控制台输出能看到打印的不是'ab'而是('ab',),这下s1不再是一个string,而变成了一个tuple
  • 第5行的字符串拼接语句, u'甲'和u'乙'都是string,而s1是tuple,作为一个强类型的语言python它当然是不能忍的,于是抛出TypeError错误。

扩展阅读

其实python2的逗号操作符不光针对字符串,任何对象后面跟了逗号后其返回值类型都会被设置为tuple,比如

>>> a = 1,

>>> print a
(1,)
>>> b = 2 + a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
>>> b = '2' + a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'tuple' objects
>>> b = '我' + a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'tuple' objects
>>> b = u'我' + a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, tuple found

看上述交互式操作,变量a被整成了一个元素是int的tuple,然后变量b的赋值就出现各种错误,诸君自己体会一下。

另外如果是ASCII字符串跟tuple拼接,则只会报无法拼接;如果是UNICODE字符串跟tuple拼接,则会报文章标题错误,这也给大家造成了干扰。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值