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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM