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?
Related
This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 1 year ago.
I wondering why the following tests return False:
Suppose I have 2 simple strings:
str0 = "trade"
str1 = "`trade"
I don't understand why the following tests in python return False:
str1.replace("`", "") is str0
And,
"".join(list(str1)[1:]) is str0 => False
Thanks for your education!
In Python, is compares two objects in memory, == compares their values. Since your two variables are stored at two different places in memory, your comparison using is evaluates to false.
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.
This question already has answers here:
Why isn't "is" comparison used in place of "==" for primitive types?
(1 answer)
Boolean identity == True vs is True
(7 answers)
Is there only one True and one False object in Python?
(2 answers)
Closed 2 years ago.
I want to check if a variable is True (not just its truthiness).
This is easily checked like this:
>>> a = 1
>>> isinstance(a, bool) and a
False
>>> a = True
>>> isinstance(a, bool) and a
True
Of course, that is totally fine. However, the same behaviour can be seen in the following code:
>>> a = 1
>>> a is True
False
>>> a = True
>>> a is True
True
In my opinion, the second snippet is a bit more readable (if you understand how is works). With Python 3.8, I get a SyntaxWarning when executing the second snippet. Would the second example work with all Python implementations? Is there a guarantee that bool objects of the same value are identical in this way? I believe I have read somewhere that this is not guaranteed for int objects. Is it ever ok to check literal values with is like this?
This question already has answers here:
comparing two strings with 'is' -- not performing as expected
(3 answers)
Closed 3 years ago.
curious to know the reason for following
x='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
y='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
x is y
#output : True
x='a'*21
y='a'*21
x is y
#output : False
Q1: since string interning is done for string literals then why not for 'a'*21 ? is it not a string literal?
Q2: is it because expression 'a'*21 is evaluated at run-time and interning is done at runtime?
#
s1 = "strin"
s2 = "string"
s1+"g" is s2
# output : False
# Explaination : Above code involves a run-time concatenation, the result of which is not automatically interned
Q3: How to know if an expression is going to be evaluated at run-time or compile time?
is will return True if two variables point to the same object, == will return True if the objects referred to by the variables are equal. If you try:
s1 = "strin"
s2 = "string"
s1+"g" == s2
# True
x='a'*21
y='a'*21
x == y
True
In your first case, Python was intelligent enough to use one single object to refer to the literal string you described twice. This is generally not the case.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
String comparison in Python: is vs. ==
When is the == operator not equivalent to the is operator? (Python)
I'm pretty new to Python still. I heard someone say use is, not == because "this isn't C". But I had some code x is 5 and it was not working as expected.
So, following proper Python/PEP style, when is the time to use is and when is the time to use == ?
You should use == to compare two values. You should use is to see if two names are bound to the same object.
You should almost never use x is 5 because depending on the implementation small integers might be interned. This can lead to surprising results:
>>> x = 256
>>> x is 256
True
>>> x = 257
>>> x is 257
False
The two operators have different meaning.
is tests object identity. Do the two operands refer to the same object?
== tests equality of value. Do the two operands have the same value?
When it comes to comparing x and 5 you invariably are interested in the value rather than the object holding the value.