Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Examples for string find in Python

I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1.

like image 814
Joan Venge Avatar asked Mar 23 '09 18:03

Joan Venge


People also ask

How do I find a string in python?

String find() in Python Just call the method on the string object to search for a string, like so: obj. find(“search”). The find() method searches for a query string and returns the character position if found. If the string is not found, it returns -1.

What is an example of a string in python?

Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello".

What is the use of find () in string?

String find is used to find the first occurrence of sub-string in the specified string being called upon. It returns the index of the first occurrence of the substring in the string from given starting position. The default value of starting position is 0.

What is the python Find () method used for?

The find() method finds the first occurrence of the specified value. The find() method returns -1 if the value is not found.


2 Answers

I'm not sure what you're looking for, do you mean find()?

>>> x = "Hello World" >>> x.find('World') 6 >>> x.find('Aloha'); -1 
like image 129
Paolo Bergantino Avatar answered Oct 14 '22 16:10

Paolo Bergantino


you can use str.index too:

>>> 'sdfasdf'.index('cc') Traceback (most recent call last):   File "<pyshell#144>", line 1, in <module>     'sdfasdf'.index('cc') ValueError: substring not found >>> 'sdfasdf'.index('df') 1 
like image 36
SilentGhost Avatar answered Oct 14 '22 16:10

SilentGhost