3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで文字列の"True"/"False"をboolとして判別する

Last updated at Posted at 2019-08-16

True/False

Python で文字列の "True""False" を bool 型として判定したいときに、どうすればいいか考えていました1

要件としてはこんな感じで:

  • 型が文字列だったら、文字列の内容で True/False を判定する
  • それ以外の型だったら、組み込み関数 bool() に渡して判定してもらう

いちおう書けたのですが、もっといい方法がありそうな気も……。

def is_true(bexp):
  if type(bexp) == str:
    return bexp.lower() in ('true', 'yes', 'on', 'enable')
  return bool(bexp)

これはこれで、コンパクトにまとまっているので、まあいいかな。どの文字列を True 扱いにするのかも分かりやすいですし。

追補

渡すものが文字列と決まっていて(Noneもないなら)、かつ True に絞るなら、もっとずっとシンプルになりますね。

result = bool_string.lower() == 'true'

ちょっと分かりにくい??

追補2

コメントで、速くて見やすいコードをいただきました!
ありがとうございます! @shiracamus

def is_true(value):
    return False if value == 'False' else bool(value)

今は修正されて見られなくなっていますが、eval を使うのは盲点でした。

eval('True')

変な値が入ると落ちますが、渡す値が確実に "True"/"False" の2値なら、スマートで素敵です。

>>> eval('True')
True
>>> eval('true')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'true' is not defined
  1. ふと思いついて試してみた bool('False')True になったのでした。

3
2
5

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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?