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..
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!")
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.
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 ( >= ).
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
).
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'] )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With