string object behavior in python [duplicate] - python

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.

Related

When is it ok to check for literal values with "is" in Python? [duplicate]

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?

Unexpected output with "is" keyword [duplicate]

This question already has answers here:
"is" operator behaves unexpectedly with integers
(11 answers)
Closed 4 years ago.
I am unable to figure out the output of the following program
big_num_1 = 1000
big_num_2 = 1000
small_num_1 = 1
small_num_2 = 1
big_num_1 is big_num_2 # False
small_num_1 is small_num_2 # True
What is happening above?
Why is one False and other True.
Source: https://luminousmen.com/post/python-interview-questions-senior
Because is compares the identity of two objects (that is, if they're exactly the same object.) You want to test for equality, and for that you must use the == operator:
big_num_1 == big_num_2
=> True
small_num_1 == small_num_2
=> True
In case you're wondering why this example worked:
small_num_1 is small_num_2
=> True
It's because Python caches small (between -5 and 256) int objects internally, so the objects used in the comparison were taken from the cache and were the same. big_num_1 and big_num_2 are greater than 256, so they're represented by two different objects, and the identity test fails.

Why hyphen(-) behaves peculiarly in python strings? [duplicate]

This question already has answers here:
Python string interning
(2 answers)
Are strings cached? [duplicate]
(1 answer)
About the changing id of an immutable string
(5 answers)
Closed 4 years ago.
I found a peculiar behavior while going through Python 3 data types especially string. If two strings a and b have the same value then a is b becomes True (Strings must not contain hyphen of course).
If:
>>> a = 'string_without_hyphen'
>>> b = 'string_without_hyphen'
Then:
>>> a is b
True
>>> a == b
True
But if:
>>> a = 'string-with-hyphen'
>>> b = 'string-with-hyphen'
Then,
>>> a is b
False
>>> a == b
True
which confused me.
Why is this happening?
Because moon rays and unicorns implementation details.
The is operator compares objects by identity, not by content.
The Python implementation you're using may or may not decide to reuse the same string object for both a and b, if it feels like it, since strings are immutable in Python. The same may or may not occur for integers (and in fact, this also happens with Java's Integers if they're sufficiently small).
The gist is: never use is unless you really do need identity (address) comparison; things may be weird. Use == instead.

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 is vs == [duplicate]

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.

Categories

Resources