user7618149 user7618149 - 1 year ago 217
Python Question

Boolean evaluation of a string without conditionals

I'm trying to figure out the solution to this particular challenge and so far I'm stumped.

Basically, what I'm looking to do is:

  1. Check if substring
    exists in string

  2. If
    exists in
    , return the boolean

However, I am not allowed to use any conditional statements at all.

Maybe there is a way to do this with objects?

Answer Source

There is always str.__contains__ if it's needed as a function somewhere:

In [69]: str.__contains__('**foo**', 'foo')
Out[69]: True

This could be used for things like filter or map:

sorted(some_list, key=partial(str.__contains__,'**foo**'))

The much more common usecase is to assign a truth value for each element in a list using a comprehension. Then we can make use of the in keyword in Python:

In[70]: ['foo' in x for x in ['**foo**','abc']]
Out[70]: [True, False]

The latter should always be preferred. There are edge cases where only a function might be possible.

But even then you could pass a lambda and use the statement:

sorted(some_list, key=lambda x: 'foo' in x)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download