LoginSignup
12
10

More than 5 years have passed since last update.

Python3でTypeError: must be str, not {型}となったときの対応方法

Posted at
  • 環境
    • OS : macOS Mojave バージョン10.14.2
    • Python : 3.6.5

事象 : Pythonに TypeError: must be str, not list と怒られた

sys.py
import sys

print('Path : ' + sys.path)
print('Version : ' + sys.version)
$ python3 sys.py 
Traceback (most recent call last):
  File "sys.py", line 3, in <module>
    print('Path : ' + sys.path)
TypeError: must be str, not list

原因 : 文字でないものを文字で扱おうとするから

$ python3
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 03:03:55) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(type(sys.path))
<class 'list'>
# ↑'str'ではなく'list'です

対応 : 文字にしてから扱う

sys.py
import sys

sys_path = str(sys.path)
print('Path : ' + sys_path)
print('Version : ' + sys.version)
$ python3 sys.py 
Path : ['/Users/mana/Dropbox/ApacheDcumentRoot', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages']
Version : 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 03:03:55) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
12
10
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10