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?

Matthias
  • 105
  • 10
  • 1
    this question doesn't exactly answer your question. but it's explanations might help you understand how to do it. https://stackoverflow.com/q/14695773/7025986 – ganjim Jan 17 '19 at 16:54
  • 3
    Use **operator** : https://stackoverflow.com/questions/2983139/assign-operator-to-variable-in-python – BadRequest Jan 17 '19 at 16:55
  • Try this: http://tomerfiliba.com/blog/Infix-Operators/ – Aaron_ab Jan 18 '19 at 00:07

1 Answers1

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
Primusa
  • 13,136
  • 3
  • 33
  • 53