James Bradbury
James Bradbury

Reputation: 1758

Pythonic way to find any item from a list within a string

The problem is simple enough. I'm writing a function which returns true if the string contains any of the illegal names.

line is a string.

illegal_names is an iterable.

def has_illegal_item(line, illegal_names):
    illegal_items_found = False
    for item in illegal_names:
        if item in line:
            illegal_items_found = True
            break
    return illegal_items_found

So this works fine, but it seems a bit clumsy and long-winded. Can anyone suggest a neater and more pythonic way to write this? Could I use a list comprehension or regex?

Upvotes: 3

Views: 320

Answers (3)

Kracekumar
Kracekumar

Reputation: 20419

I go with @larsmans solution, but there another ways of doing it.

def check_names(line, names):
    #names should be set
    parsed_line = set(line.replace(',', '').split())
    return bool(parsed_line.intersection(names))

This can also be written using lambda

In [57]: x = lambda line, names: bool(set(line.replace(",", "").split()).intersection(names))

In [58]: x("python runs in linux", set(["python"]))
Out[58]: True

lamdba version can be overkill of readability

Upvotes: 0

Colin O'Coal
Colin O'Coal

Reputation: 1427

let's have a look on following sample:

line = "This is my sample line with an illegal item: FOO"
illegal_names = ['FOO', 'BAR']

and you want now to find out whether your line contains one of the illegal names, then you do this with the widespread List Comprehension and a length check:

is_correct = not bool(len([ hit for hit in illegal_names if hit in line ]))
# or
is_correct = len([ hit for hit in illegal_names if hit in line ]) == 0

Pretty easy, short and in relation to other lambda version easy to read and unterstand.

-Colin-

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363487

any(name in line for name in illegal_names)

Upvotes: 6

Related Questions