2

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?

3

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

Great, thanks! In my case, I can just switch string1 and string2 within the function and use operator.contains.
@Matthias Happy to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.