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