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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-19
  • 2022-03-07
  • 2022-01-01
  • 2021-12-02
  • 2021-06-28
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-27
  • 2021-07-30
  • 2022-03-10
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案