Nilesh Nar
Nilesh Nar

Reputation: 169

Substring Comparison in python

If i have List PhoneDirectory Eg:

['John:009878788677' , 'Jefrey:67654654645' , 'Maria:8787677766']

Which is the function that can be use to compare the Presence of Substring (Eg: Joh) in each entry in the List .

I have tried using

if(PhoneDirectory.find(Joh) != -1)

but it doesnt work

kindly Help..

Upvotes: 6

Views: 28556

Answers (5)

Tony Veijalainen
Tony Veijalainen

Reputation: 5565

if any(entry.startswith('John:') in entry for entry in PhoneDirectory)

But I would prepare something with two elements as you list of strings is not well suited to task:

PhoneList = ['John:009878788677' , 'Jefrey:67654654645' , 'Maria:8787677766']

numbers = { a:b 
            for item in PhoneList
            for a,_,b in (item.partition(':'),)
            }

print numbers
print "%s's number is %s." % ( 'John', numbers['John'] )

Upvotes: 3

Odomontois
Odomontois

Reputation: 16328

If performance counts for this task use some SuffixTree implementation. Or just make any DBMS engine do the indexing job.

Upvotes: 0

Justin Ardini
Justin Ardini

Reputation: 9866

Since no one has recommended this yet, I would do:

all_johns = [p for p in PhoneDirectory if 'Joh' in p]

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 882711

If you want to check each entry separately:

for entry in PhoneDirectory:
    if 'John' in entry: ...

If you just want to know if any entry satisfies the condition and don't care which one:

if any('John' in entry for entry in PhoneDirectory):
    ...

Note that any will do no "wasted" work -- it will return True as soon as it finds any one entry meeting the condition (if no entries meet the condition, it does have to check every single one of them to confirm that, of course, and then returns False).

Upvotes: 19

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181460

You can do a split on ":" and look for occurrences of what you are looking for in the first element of the resulting array.

dir = ['John:009878788677' , 'Jefrey:67654654645' , 'Maria:8787677766'];
for a in dir:
    values = a.split(":")
    if values[0] == "John":
        print("John's number is %s" % (values[1]))

Upvotes: 0

Related Questions