0

From what I understand I can compare strings with is and ==. Is there a way I can partially apply these functions?

For example:

xs = ["hello", "world"]
functools.filter(functools.partial(is, "hello"), xs)

Gives me:

functools.filter(functools.partial(is, "hello"), xs)
                                    ^
SyntaxError: invalid syntax
Georgy
  • 12,464
  • 7
  • 65
  • 73
  • 3
    `is` is not a function. Neither is `==`. – Daniel Roseman May 01 '15 at 11:52
  • 1
    What do you mean by partially ? What is your aim ? – ZdaR May 01 '15 at 11:52
  • 2
    You should [always](http://stackoverflow.com/questions/6570371/when-to-use-and-when-to-use-is) compare strings with `==`. Comparing object with `is` checks for identity, and should only be used for singletons like `None`. – Bas Swinckels May 01 '15 at 11:52
  • There are functions like `str.startswith("target")` and `str.endswith("target")` as well as testing for a string within another by `str.find("target") > -1` but it depends on what exactly you need to test. – SuperBiasedMan May 01 '15 at 11:54

2 Answers2

4

You could use operator.eq:

import operator
import functools
xs = ["hello", "world"]
functools.filter(functools.partial(operator.eq, "hello"), xs)

yields

['hello']

operator.eq(a, b) is equivalent to a == b.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
2

I don't know why you would want to use partial here. Much easier to write it directly as a function, for instance by using lambda:

functools.filter(lambda x: x == 'hello', xs)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895