Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find vs in operation in string python

Tags:

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  
like image 605
user765443 Avatar asked Aug 26 '13 06:08

user765443


People also ask

What is the difference between index () & Find () in strings?

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.

How do I find a particular substring in a string Python?

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.

What is the difference between using in and find ()? In Python?

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.

How do you check if a word is in a string Python?

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.


1 Answers

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 
like image 113
DhruvPathak Avatar answered Oct 12 '22 01:10

DhruvPathak