I need to find pattern into string and found that we can use in or find also. Could anyone suggest me which one will be better/fast on string. I need not to find index of pattern as find can also return the index of the pattern.
temp = "5.9" temp_1 = "1:5.9" >>> temp.find(":") -1 >>> if ":" not in temp: print "No" No
Both index() and find() are identical in that they return the index position of the first occurrence of the substring from the main string. The main difference is that Python find() produces -1 as output if it is unable to find the substring, whereas index() throws a ValueError exception.
Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1. Parameters: sub: Substring that needs to be searched in the given string.
The 'in' operator is used to check if a value exists in a sequence or not. Evaluates to true if it finds a variable in the specified sequence and false otherwise. find() method The find() method returns the lowest index of the substring if it is found in given string.
The simplest way to check if a string contains a substring in Python is to use the in operator. This will return True or False depending on whether the substring is found. For example: sentence = 'There are more trees on Earth than stars in the Milky Way galaxy' word = 'galaxy' if word in sentence: print('Word found.
Use in
, it is faster.
dh@d:~$ python -m timeit 'temp = "1:5.9";temp.find(":")' 10000000 loops, best of 3: 0.139 usec per loop dh@d:~$ python -m timeit 'temp = "1:5.9";":" in temp' 10000000 loops, best of 3: 0.0412 usec per loop
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