Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring Comparison in python

Tags:

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..

like image 587
Nilesh Nar Avatar asked Aug 19 '10 17:08

Nilesh Nar


People also ask

How do you compare a substring to a string in Python?

It returns a Boolean (either True or False ). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring: fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!")

How do you tell if a string contains a substring in Python?

The easiest and most effective way to see if a string contains a substring is by using if ... in statements, which return True if the substring is detected. Alternatively, by using the find() function, it's possible to get the index that a substring starts at, or -1 if Python can't find the substring.

Can you use == to compare strings in Python?

Python comparison operators can be used to compare strings in Python. These operators are: equal to ( == ), not equal to ( != ), greater than ( > ), less than ( < ), less than or equal to ( <= ), and greater than or equal to ( >= ).


2 Answers

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).

like image 63
Alex Martelli Avatar answered Oct 17 '22 00:10

Alex Martelli


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'] )
like image 37
Tony Veijalainen Avatar answered Oct 17 '22 00:10

Tony Veijalainen