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.
I wonder if distutils.util.strtobool () + bool (), which will be described later, should be dropped.
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
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.
None
False
0
, 0L
, 0.0
, 0j
.''
, ()
, []
.{}
.__nonzero__
or __len__
methods defined, and those methods return an integer value of zero or a bool
value of
False``.$ 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
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
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
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 ''
――If there is another good way, please leave a comment.
Recommended Posts