0

I want to compare 2 strings with each other.

I tried 'in', '==' and 'is' operator. But it is not working properly.

1st code:

myStrings = ['test1', 'test2', 'test3', 'test11', 'test111', 'test56']

for elem in myStrings:
    if 'test1' in elem:
        print('success')

2nd Code:

myStrings = ['test1', 'test2', 'test3', 'test11', 'test12', 'test56']

for elem in myStrings:
    if 'test1' is elem[0:len('test1')]:
        print('success')

Expected: success should be printed only once. But it is printing 3 times. It is comparing successfully with 'test11' and 'test12' also.

Sorry, I did not explain the question completely.

The length of strings in the list is not fixed. It is variable. And string 'test1' is substring for multiple strings.

Now, in next step I also want to compare 'test11' to elements of the list. But here it is failing. Since it is matching to 'test11' and 'test111'.

Sorry for the language.

atg
  • 204
  • 3
  • 18

2 Answers2

1

Use == instead of is.

Difference between == and is operator in Python. The == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object or not.

A stackoverflow post about it: Is there a difference between "==" and "is"?

myStrings = ['test1', 'test2', 'test3', 'test11', 'test12', 'test56']

for elem in myStrings:
    if 'test1' == elem:
        print('success')

output:

success
Stef van der Zon
  • 633
  • 4
  • 13
0

Try checking whether the element of the list is equivalent to 'test' :

myStrings = ['test1', 'test2', 'test3', 'test11', 'test12', 'test56']
for elem in myStrings:
   if elem=='test1':
     print('success')

OUTPUT :

success
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56