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,870 points

closed Sep 19, 2018 by Priyaj 35 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,160 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
53 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 ariaholic
• 7,340 points
50 views
0 votes
2 answers

Check a number is Prime or not in Python

number = int(input("Enter the Number")) if(number==1):     print(number,"is not prime ...READ MORE

answered 4 days ago in Python by Anand Kumar
378 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,520 points

edited Dec 11, 2018 by Nymeria 781 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
• 56,580 points
66 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
• 56,580 points
97 views
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,160 points
59 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,160 points
66 views