How to parse string representations of bool into bool in python? [duplicate] - python

This question already has answers here:
Converting from a string to boolean in Python
(39 answers)
Closed last month.
My scenarios where I need it:
User is inputting True or False and it is parsed as str by default. I cannot change the parsing type as python 3+ parses as str (Using Python 3.8)
So when I parse bool(input('Enter True or False')), it returns True regardless since default bool function only returns False when there is an empty string. True otherwise.
I have a json for which I need it.
It has following representation:
list_of_visits ='''{"Museum": "True",
"Library": "True",
"Park": "False"}
'''
Note that I cannot have its representation without qoutes as:
list_of_visits ='''{"Museum": True,
"Library": True,
"Park": False}
'''
Cause parsing this as follows throws error:
jsonic = json.loads(list_of_visits)
jsonic
But I need to parse from int and float as well at some places and I cannot write functions for each type separately .
I am trying to build a one-stop solution which might inherit functionality from bool() and does this conversion as well and I can use it everywhere
i.e. solution which can not only perform traditional bool() operations but also able to parse string representations.
Currently I do following steps:
if type(value) == str and value =='True':
reprs = True
elif type(value) == str and value =='False':
reprs = False
else:
reprs = bool(value)

You can define your own function which may work in all scenarios as:
def get_bool(key):
return value if value := {'True':True, 'False':False}.get(key) else bool(key)
For a single value such as input you might parse it as:
get_bool('False')
which returns: False
For jsons like that you might do:
from toolz.dicttoolz import valmap
valmap(get_bool, jsonic)
which returns:
{'Museum': 1, 'Library': 1, 'Park': 0}
For 3.7 and lower:
I'm in love with walrus operator since it came out in python 3.8. Anyone looking for lower versions might need some repetitions:
def get_bool(key):
return {'True':True, 'False':False}.get(key) if key.title() in {'True':True, 'False':False}.keys() else bool(key)
Note that though it does work for every case, your JSON representation is wrong. JSONs can have boolean values so can the string representations of JSONs. But you got to use javascript syntax as true and false instead of Python's True & False. Since JSON is a javascript notation.

Related

How to convert string to Boolean in Python

I came across this question for the interview. I had to convert the string to Boolean and return the Boolean value
For ex s="3>1>5" => false
I tried using
ans= bool(s)
But I always get the answer as True even though the above example gives False if we don't pass it as a string
You must be looking for eval(string)
>>> eval("3>1>5")
False

safely comparing two strings in Python [duplicate]

This question already has an answer here:
Python unicode equal comparison failed
(1 answer)
Closed 5 years ago.
So I want to compare two strings, sometimes one of them will be of type "unicode" and sometimes one of them will be of type "str".
This is what I've currently got:
def poll_change(self):
''' Returns a tuple (has_changed, new_element_str) '''
new_element = self.find_element()
old_element = self.read_element_str()
# TODO: handle compare correctly
if type(new_element) is not type(old_element):
changed = False
else:
changed = new_element != old_element
return changed, new_element
what would be the best solution for this?
Right now I am just returning False if the types of the strings are unequal, but I would like to compare them anyways.
I would get an error if I would compare unicode with str for example.
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/difflib.py:433: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
a[besti-1] == b[bestj-1]
I am using Python 2.7
>>> u"a" == "a"
True
>>> "a" == "a"
True
>>> u"a" == u"a"
True
So what is the problem? Or do you mean you want to compare type too?

python - str containing whitespace characters and int(str)

I'm trying to write a really simple function. It should return True if given object is a digit (0-9), False otherwise. Here are examples of input and desired output:
is_digit("") => False
is_digit("7") => True
is_digit(" ") => False
is_digit("a") => False
is_digit("a5") => False
My code works for the above examples.
def is_digit(n):
try:
return int(n) in range(0, 10)
except:
return False
Trouble is, the function returns True for n = "1\n" when it should return False. So, a string like "1" should be converted to integer and is a digit, but a string like "1\n" should not, yet I don't know how to get around that. How can I account for string literals?
P.S. If my title is lame, advice on renaming it is welcome.
You don't need to define a custom function for this. There is a built-in function for this, namely isdigit().
You can use it as: "a5".isdigit() or "1/n".isdigit().In both cases it will return False.
First you have to convert your literals into string then you can apply isdigit.
You can not apply isdigit directly to number. It will throw an error
AttributeError: 'int' object has no attribute 'isdigit'
You have to typecast your number in string.
eg:
In [3]: str(0).isdigit()
Out[3]: True
or
In [1]: "0".isdigit()
Out[1]: True

How to control length of the result of string.format(bool_value) in Python?

What the equivalent way to str.format function for converting booleans into strings?
>>> "%5s" % True
' True'
>>> "%5s" % False
'False'
Please note the space in ' True'. This always makes the length the same for 'True' and 'False'.
I've check the methods in this post:
How are booleans formatted in Strings in Python?
None of them can do the same thing.
You can use type conversion flags to do what you wanted:
'{:_>5}'.format(True) # Oh no! it's '____1'
'{!s:_>5}'.format(True) # Now we get '_True'
Note the !s. I used an underscore to show the padding more clearly. It also works with f-strings:
f'{True:_>5}' # '____1'
f'{True!s:_>5}' # '_True'
Relevant documentation:
6.1.3. Format String Syntax
[...]
The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling __format__(), the normal formatting logic is bypassed.
Three conversion flags are currently supported: '!s' which calls str() on the value, '!r' which calls repr() and '!a' which calls ascii().
Some examples:
"Harold's a clever {0!s}" # Calls str() on the argument first
"Bring out the holy {name!r}" # Calls repr() on the argument first
"More {!a}" # Calls ascii() on the argument first
You can use the str() function. More about it here.
Here are some examples:
x = str(True)
y = False
print( type(x) )
<class 'str'> # This is a string
print( type(y) )
<class 'bool'> # This is a boolean
I found that "{:>5}".format(str(True)) works fine.
The output is exactly the same as "%5s" % True, ie ' True'.
So the length of "{:>5}".format(str(bool_value)) is alway 5, no matter bool_value is True or False.
Of course you may change the length or the alignment direction as you want. eg. "{:6}".format(str(True)) outputs 'True '.
Not sure if I got idea correctly but if some variable x results in True or False, You can write str(x); if not a case, sorry just try explaining Q in more detailed way

Bool as int? How does python evaluate [duplicate]

This question already has answers here:
Python Bool and int comparison and indexing on list with boolean values
(4 answers)
Closed 4 years ago.
In [1]: a=5
In [2]: print(["is odd", "is even"][a % 2 == 0])
is odd
In [3]: [a%2 == 0]
Out[3]: [False]
What I understood is a % 2 == 0 evaluates to True or False.
So if it is True then that is equivalent to 1 and using list indices it's going to print 'is even'.
I've read this and came to know bool is an instance of int.
So when used as in index bool evaluates to it's equivalent number i.e 0 or 1.
My question
Based on intuition we can know whether it's going to be an int or bool
But how does Python know? Does it have any criteria when to use as bool and when to use as int? Anything from Python3 documentation would be appreiated.
In Python 2.x this is not guaranteed as it is possible for True and False to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.
In Python 3.x True and False are keywords and will always be equal to 1 and 0.
Under normal circumstances in Python 2, and always in Python 3:
False object is of type bool which is a subclass of int:
object
|
int
|
bool
It is the only reason why in your example, ['zero', 'one'][False] does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define the __index__ method (thanks mark-dickinson).
Edit:
It is true of the current Python version, and of that of Python 3. The docs for Python 2.6 and the docs for Python 3 both say:
There are two types of integers: [...] Integers (int) [...] Booleans (bool)
and in the boolean subsection:
Booleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.
So booleans are explicitly considered as integers in Python 2.6 and 3.
The bool instances, True and False, are separate from the int instances, 0 and 1. The thing is that the bools behave like integers in many contexts. Such as True+True which is 2. However if we check if they are the same object we see it is not: True is 1. On the other hand it is true that True is True. Here's an example which behaves like integers but are printed as True and False and compares differently with is.
class Bool(int):
def __repr__(self):
return 'True' if self==1 else 'False'
https://docs.python.org/3/library/stdtypes.html#bltin-boolean-values

Categories

Resources