How to partially compare two string value inside a IF statement using or operator in Python

Question:

I want to compare one variable value which is a string with an another string value in a IF statement using a python code.

Expectation:

Variable Name and Value:: v1=’purchased’
String Value:: string=’purchase’

If both (v1 and string) are not equal then,

print "Both strings are not equal".

Outcome:

v1 = 'purchased'

if (v1 not like 'pur%') or (v1 != 'ordered'):
    print("Both strings are not equal", v1)  # return if true
else:
    print("Both strings are equal", v1)  # return if false

Scenario 1: While passing v1 as "purchase" getting "Both strings are not equal". It should give me "Both strings are equal". As I am trying to match it partially.

Scenario 2: When giving "ordered" it is giving same "Both strings are not equal". It should give me "Both strings are equal".

Asked By: user3040157

||

Answers:

With OR and different you’ll always end up in if case. To compare strings change to the following:

v1 = 'purchase'

if v1 != 'purchased' and v1 != 'ordered':
    print("Both strings are not equal", v1)  # return if true
else:
    print("Both strings are equal", v1)  # return if false

an other way is to use "in" operator like this:

v1 = 'purchase'
    
if v1 not in ['purchased', 'ordered']:
    print("Both strings are not equal", v1)  # return if true
else:
    print("Both strings are equal", v1)  # return if false
Answered By: s_frix

You should use and statement,
in your case if v1 == ‘purchased’ then v1 != ‘ordered’ so the if condition is satisfied.

if v1 == ‘ordered’ then v1 != ‘purchased so the if condition is satisfied too.

try (v1 != 'purchased') and (v1 != 'ordered')

or (v1 == 'purchased') or (v1 == 'ordered')

Answered By: Berni

i think the error comes from your ().

Try this instead:

v1 = 'ordered'

if v1 == 'purchased' or v1 == 'ordered':
    print(f'Both Strings are equal {v1}')
else:
    print(f'Both Strings are not equal {v1}')  

and i also used f strings for readability.

Hope i helped.

Answered By: HaggisBonBon
if string1 == "value1" or string2 == "value2":
    Do Something
else:
    Do something else
Answered By: gabrsafwat
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.