String → Bool value conversion in Python Consideration

The beginning of the matter

I want to convert a String value of "false" to a Bool value of False, is there a good way?

Going a little further, it looks like [Boolean.Parse] in C # (http://msdn.microsoft.com/ja-jp/library/system.boolean.parse%28v=vs.110%29.aspx). Is there anything? That is.

Conclusion at this stage

I wonder if distutils.util.strtobool () + bool (), which will be described later, should be dropped.

Previous conclusion 1

Before that, I was thinking about this.

def CBool( value ):
    if isinstance( value, str ) and value.lower() == "false":
        return False
    return bool( value )
$ python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def CBool( value ):
...     if isinstance( value, str ) and value.lower() == "false":
...         return False
...     return bool( value )
... 
>>> CBool( "False" )
False
>>> CBool( "false" )
False
>>> CBool( 0 )
False
>>> CBool( [] )
False
>>> CBool( "" )
False
>>> CBool( "True" )
True
>>> CBool( 1 )
True
>>> CBool( [ "hoge" ] )
True
>>> CBool( "hoge" )
True

Trial

bool () built-in function

With this, the problem mentioned in "The beginning of things" cannot be solved.

According to the official Python 2.6 documentation 5. Embedded> 5.1. Truth Value Test, the following values may be false: , Otherwise it is True.

$ python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> bool( "False" )
True

json.loads()

"The beginning of the thing" can be solved, but it is different from the original usage of json.loads (), so it may be difficult for other people to understand the intention. Also, since it is assumed that the JSON value will be entered, it will not pass unless it is "false" in all lowercase letters. If set to "False", a Value Error will occur.

$ python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> json.loads( "false" )
False
>>> json.loads( "False" )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python2.6/json/decoder.py", line 338, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

ast Use module

This can also eliminate the "beginning of things". Also, ast.literal_eval () is different from simple eval () in that the conversion is narrowed down to literal values, so the risk is low even when parsing variables that do not know where the bones are. However, "false" cannot be parsed.

$ python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ast
>>> ast.literal_eval( "False" )
False
>>> ast.literal_eval( "false" )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/ast.py", line 68, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib64/python2.6/ast.py", line 67, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

Evaluate strings

This can also eliminate the "beginning of things". The intention is also easy to understand. It can also absorb the difference between uppercase and lowercase letters. However, it seems better to make it a method and put it together somewhere. However, if a variable other than a character string is entered, an error will occur.

$ python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> False if "False".lower() == "false" else True
False
>>> False if "false".lower() == "false" else True
False
>>> False if "True".lower() == "false" else True
True

Use distutils .util.strtobool

This can also eliminate the "beginning of things". The intention is also easy to understand. It also measures strings with the intention of True / False. However, if a character string that is not the conversion target is entered, an exception will occur, so pick it up properly.

$ python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import distutils.util
>>> distutils.util.strtobool( "False" )
0
>>> distutils.util.strtobool( "false" )
0
>>> bool( distutils.util.strtobool( "False" ) )
False
>>> bool( distutils.util.strtobool( "No" ) )
False
>>> distutils.util.strtobool( "True" )
1
>>> bool( distutils.util.strtobool( "True" ) )
True
>>> bool( distutils.util.strtobool( "" ) )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/distutils/util.py", line 424, in strtobool
    raise ValueError, "invalid truth value %r" % (val,)
ValueError: invalid truth value ''

in conclusion

――If there is another good way, please leave a comment.

Recommended Posts

String → Bool value conversion in Python Consideration
Conversion of string <-> date (date, datetime) in Python
[Python] Invert bool value in one line
String manipulation in python
String object methods in Python
Shapley value calculation in Python
String date manipulation in Python
6 ways to string objects in Python
Create a random string in Python
Python string
Comparison of Japanese conversion module in Python3
Generate a class from a string in Python
Python: Preprocessing in machine learning: Data conversion
Quadtree in Python --2
Python in optimization
CURL in python
Python: String concatenation
Metaprogramming in Python
Python 3.3 in Anaconda
Python string format
SendKeys in Python
python string slice
How to embed a variable in a python string
File DL, byte value and delete in Python3
Project Euler # 8 "Maximum Product in Number String" in Python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Find the divisor of the value entered in python
Python Note: When assigning a value to a string
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Python2 string type
Python string format
Constant in python
Python # string type
nCr in Python.
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
json.dumping None in python returns the string null
Put out a shortened URL string in Python
Quad-tree in Python
Insert an object inside a string in Python
Reflection in Python
Chemistry in Python
Python string inversion