參考: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