comparing strings in Python using or is [closed]

0 votes

In the following Python code:

>>> s1 = 'Hello'
>>> s2 = 'Hello'
>>> s2 is s1
True
If I compare Var1 is Var2 in a conditional statement if fails to give the correct answer but if i write Var1 == Var2 instead, it returns true. Why is that happening?
Sep 19, 2018 in Python by ana1504.k
• 7,910 points

closed Sep 19, 2018 by Priyaj 800 views
0 votes

is is used for identity testing and == is used for equality testing, i.e, is is the id(a) == id(b).

So your code will be emaluated in the following way:

>>> a = 'hi'
>>> b = ''.join(['h', 'i'])
>>> a == b
True
>>> a is b
False
answered Sep 19, 2018 by SDeb
• 13,300 points

Related Questions In Python

0 votes
1 answer

Comparing strings in Python

Convert both the strings to either uppercase ...READ MORE

answered May 28, 2018 in Python by Nietzsche's daemon
• 4,260 points
794 views
0 votes
1 answer

How does Python know whether a variable in the class is a method or a variable?

In python objects/variables are wrapped into methods ...READ MORE

answered Sep 18, 2018 in Python by aryya
• 7,460 points
1,110 views
0 votes
2 answers

Check a number is Prime or not in Python

There is an efficient way to write ...READ MORE

answered Oct 26, 2018 in Python by Priyaj
• 58,100 points
4,984 views
0 votes
1 answer

How do I use urllib to see if a website is 404 or 200 in Python?

For Python 3, try doing this: import urllib.request, ...READ MORE

answered Nov 29, 2018 in Python by Nymeria
• 3,560 points

edited Dec 11, 2018 by Nymeria 13,905 views
0 votes
1 answer

How can I print variable and string on same line in Python?

Use , to separate strings and variables while printing: print ...READ MORE

answered Sep 17, 2018 in Python by Priyaj
• 58,100 points
3,475 views
+1 vote
1 answer

Python: Print variable and string in same line

For a better understanding you can refer ...READ MORE

answered Oct 30, 2018 in Python by Priyaj
• 58,100 points
1,474 views
0 votes
2 answers
0 votes
1 answer

Is there a string 'contains' in python?

In this case, you can use the ...READ MORE

answered Sep 25, 2018 in Python by SDeb
• 13,300 points
647 views
0 votes
1 answer

Is arr.__len__() the preferred way to get the length of an array in Python?

my_list = [1,2,3,4,5,6,7] len(my_list) # 7 The same works for ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 13,300 points
895 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP