Python で文字列とリストを区別する方法は何ですか? 質問する

Python で文字列とリストを区別する方法は何ですか? 質問する

私のプログラムでは、オブジェクトが文字列、または文字列やその他の類似リストを含むリストになる場所がたくさんあります。これらは通常、JSON ファイルから読み取られます。これらは両方とも別々に処理する必要があります。現在、isinstance を使用していますが、これは最も Python らしい方法ではないと思います。もっと良い方法を知っている人はいませんか?

ベストアンサー1

モジュールをインポートする必要はありません。isinstance()str(unicodeバージョン 3 より前 -- 3 には存在しませんunicode!) で十分です。

Python 2.x:

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(u'', (str, unicode))
True
>>> isinstance('', (str, unicode))
True
>>> isinstance([], (str, unicode))
False

>>> for value in ('snowman', u'☃ ', ['snowman', u'☃ ']):
...     print type(value)
... 
<type 'str'>
<type 'unicode'>
<type 'list'>

Python 3.x:

Python 3.2 (r32:88445, May 29 2011, 08:00:24) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance('☃ ', str)
True
>>> isinstance([], str)
False

>>> for value in ('snowman', '☃ ', ['snowman', '☃ ']):
...     print(type(value))
... 
<class 'str'>
<class 'str'>
<class 'list'>

からペップ008:

オブジェクト タイプの比較ではisinstance()、タイプを直接比較するのではなく、常に を使用する必要があります。

おすすめ記事