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
Related
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.
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
I recently encountered an example of an if-else conditional statement and could not understand the rationale behind its output. The following are the statements:
if 0:
1
else:
2
Output: 2
I tried different integers in 0's place, and received 1 each time. Is this because the zero in the if condition represents False? But then why do integers other than 1 still satisfy the if condition?
Thanks!
Edit: Thank you for all your answers. I now understand that any integer except 0 in the 'if' statement will make the statement True by default, resulting in an output of 1, in this case.
Python will always attempt to determine the "truthiness" of a given value used in a boolean context. In Python any numerical value of 0 (or 0.0) is considered false, and string, dictionary, list, or other iterable (or other class that can report its length) is false if it's empty or has length of 0. Also, None and boolean False are considered false.
Other values are considered true.
More details: https://docs.python.org/2.4/lib/truth.html.
In Python, bool is a subtype of int. False has the value 0, while other non-zero integers have the subtype bool with the value True.
To see this for yourself try this: False == 0
And to see the subtypes of int try this: int.__subclasses__()
1 is considered True while 0 is False,just like in binary.
Any non-zero numeric value is evaluated as True in a conditional statement.
bool type is just a subtype of int in Python, with 1 == True and 0 == False.
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
I am parsing from a xml file and trying to build a dictionary for every context in the xml. I have done parsing successfully, and now I need to get rid of the stopwords, punctuations and numbers from the string I get.
However, for some reason, I couldn't get rid of the numbers, I have been debugging all night, hope someone could help me with it...
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
I have been checking that the method 'is_number' is working, but I don't why it still could get pass the if statement:
if (words[headIndex + index] not in cachedStopWords) and ~isNumber:
Thanks in advance!
The problem is:
~isNumber
~ is the bitwise not operator. You want the not boolean operator:
>>> ~True
-2
>>> ~False
-1
>>> not True
False
>>> not False
True
The bitwise operator will lead to ~isNumber always being a truthy value (-1 or -2), and so your if statement is entered.