Python - TypeError: unicode argument expected, got 'str'

参考:TypeError: unicode argument expected, got 'str'

Python代码:

from io import StringIO

def main():
	f = StringIO()
	f.write('Hi')
	f.write(' ')
	f.write('all')
···

解释器报错:

Traceback (most recent call last):
  File "./stringio.py", line 19, in <module>
    main()
  File "./stringio.py", line 7, in main
    f.write(str('Hi'))
TypeError: unicode argument expected, got 'str'

stackoverflow上对这个问题的解释是:

io.StringIO is confusing in Python 2.7 because it's backported from the 3.x bytes/string world.

backported: 名词解释

意思就是新版本的python3直接往这个库中加入了一些新的内容,使得该库在Python2.7中较为混乱。

解决方法是将导入语句更换为:

from io import BytesIO as StringIO

2017.3.15

posted @ 2017-03-15 20:39  Wasdns  阅读(3229)  评论(0编辑  收藏  举报