Matthias
Matthias

Reputation: 115

Compare strings with different operators in python

I'd like to compare two strings in a function with the comparison/membership operators as argument.

string1 = "guybrush"
string2 = "guybrush threepwood"

def compare(operator):
    print(string1 operator string2)

compare(==) should print False and compare(in) should print True

It's obviously not working like that. Could I assign variables to the operators, or how would I solve that?

Upvotes: 2

Views: 98

Answers (1)

Primusa
Primusa

Reputation: 13498

You can't pass in operators directly, you need a function like so:

from operator import eq

string1 = "guybrush"
string2 = "guybrush threepwood"

def compare(op):
    print(op(string1, string2))

compare(eq)
>>>False

The in operator is a little more tricky, since operator doesn't have an in operator but does have a contains

operator.contains(a, b) is the same as b in a, but this won't work in your case since the order of the strings are set. In this case you can just define your own function:

def my_in(a, b): return a in b

compare(my_in)
>>>True

Upvotes: 5

Related Questions