Метод rfind в python

Python String rfind() Method

Where in the text is the last occurrence of the string «casa»?:

Definition and Usage

The rfind() method finds the last occurrence of the specified value.

The rfind() method returns -1 if the value is not found.

The rfind() method is almost the same as the rindex() method. See example below.

Syntax

Parameter Values

Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string

More Examples

Example

Where in the text is the last occurrence of the letter «e»?:

Читайте также:  Data validation in python

txt = «Hello, welcome to my world.»

Example

Where in the text is the last occurrence of the letter «e» when you only search between position 5 and 10?:

txt = «Hello, welcome to my world.»

Example

If the value is not found, the rfind() method returns -1, but the rindex() method will raise an exception:

txt = «Hello, welcome to my world.»

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Метод rfind() и find() в Python

Метод rfind() возвращает наивысший индекс подстроки (если найден). Если не найден, возвращается -1.

Параметры

Метод rfind() в Python принимает не более трех параметров:

  • sub ‒ это подстрока, которую нужно искать в строке str .
  • start и end (необязательно) ‒ поиск подстроки выполняется в str [start: end].

Возвращаемое значение

Метод возвращает целочисленное значение:

  • Если подстрока существует внутри строки, он возвращает наивысший индекс, в котором найдена подстрока.
  • Если подстроки не существует внутри строки, возвращается -1.

Как find () и rfind () работают в Python

Пример 1: Без начального и конечного аргументов

quote = 'Let it be, let it be, let it be' result = quote.rfind('let it') print("Substring 'let it':", result) result = quote.rfind('small') print("Substring 'small ':", result) result = quote.rfind('be,') if (result != -1): print("Highest index where 'be,' occurs:", result) else: print("Doesn't contain substring")
Substring 'let it': 22 Substring 'small ': -1 Contains substring 'be,'

Пример 2: С начальным и конечным аргументами

quote = 'Do small things with great love' # Substring is searched in 'hings with great love' print(quote.rfind('things', 10)) # Substring is searched in ' small things with great love' print(quote.rfind('t', 2)) # Substring is searched in 'hings with great lov' print(quote.rfind('o small ', 10, -1)) # Substring is searched in 'll things with' print(quote.rfind('th', 6, 20))

Метод find() возвращает индекс первого вхождения подстроки (если найден). Если не найден, возвращается -1.

Параметры

Метод find() в Python принимает максимум три параметра:

  • sub ‒ это подстрока, которую нужно искать в строке str .
  • start и end (необязательно) ‒ диапазон str [start: end], в котором ищется подстрока.

Возвращаемое значение

Метод возвращает целочисленное значение:

  • Если подстрока существует внутри строки, он возвращает индекс первого появления подстроки.
  • Если подстроки не существует внутри строки, возвращается -1.

Работа метода find()

работа метода find()

Пример find(): Без начального и конечного аргументов

quote = 'Let it be, let it be, let it be' # first occurance of 'let it'(case sensitive) result = quote.find('let it') print("Substring 'let it':", result) # find returns -1 if substring not found result = quote.find('small') print("Substring 'small ':", result) # How to use find() if (quote.find('be,') != -1): print("Contains substring 'be,'") else: print("Doesn't contain substring")
Substring 'let it': 11 Substring 'small ': -1 Contains substring 'be,'

Пример с аргументами start и end

quote = 'Do small things with great love' # Substring is searched in 'hings with great love' print(quote.find('small things', 10)) # Substring is searched in ' small things with great love' print(quote.find('small things', 2)) # Substring is searched in 'hings with great lov' print(quote.find('o small ', 10, -1)) # Substring is searched in 'll things with' print(quote.find('things ', 6, 20))

Источник

Методы find() и rfind() в Python

Метод find() в Python используется для поиска индекса подстроки в строке.

Эта функция возвращает наименьший индекс в строке, где подстрока «sub» находится внутри среза s [начало: конец].

Начальное значение по умолчанию – 0, и это необязательный аргумент.

Конечное значение по умолчанию – длина строки, это необязательный аргумент.

Если подстрока не найдена, возвращается –1.

Нам следует использовать метод find(), когда мы хотим узнать позицию индекса подстроки. Для проверки наличия подстроки мы можем использовать оператор in.

Примеры

Давайте посмотрим на несколько простых примеров метода find().

s = 'abcd1234dcba' print(s.find('a')) # 0 print(s.find('cd')) # 2 print(s.find('1', 0, 5)) # 4 print(s.find('1', 0, 2)) # -1

rfind()

Метод rfind() похож на find(), за исключением того, что поиск выполняется справа налево.

s = 'abcd1234dcba' print(s.rfind('a')) # 11 print(s.rfind('a', 0, 20)) # 11 print(s.rfind('cd')) # 2 print(s.rfind('1', 0, 5)) # 4 print(s.rfind('1', 0, 2)) # -1

Как найти все индексы для подстроки

Строка find() и rfind() в Python возвращает первый совпавший индекс. Мы можем определить пользовательскую функцию для поиска всех индексов, по которым находится подстрока.

def find_all_indexes(input_str, search_str): l1 = [] length = len(input_str) index = 0 while index < length: i = input_str.find(search_str, index) if i == -1: return l1 l1.append(i) index = i + 1 return l1 s = 'abaacdaa12aa2' print(find_all_indexes(s, 'a')) print(find_all_indexes(s, 'aa'))

Источник

rfind() in Python

Python Certification Course: Master the essentials

In Python, the rfind() method returns the index of the last occurrence of a substring in the given string, and if not found, then it returns -1 .

Syntax of rfind() function in Python

Syntax of the rfind() method in Python is as follows:

The string here is the given string in which the value's last occurrence has to be searched. Three arguments: value , start , and end can be passed to the rfind() method.

Parameters of rfind() in python

Parameters of the rfind() method in Python are as follows:

  • value: The substring to search for in the given string.
  • start (optional): The starting position from where the value needs to be checked in the given string. It is an optional parameter and 0 by default.
  • end (optional): The ending position till where the value needs to be checked in the given string. It is an optional parameter and is at the end of the given string by default.

Return Values of rfind() function in Python

The rfind() method returns the index of the last occurrence of a value in the given string. If the value is not found in the given string, then the return value is -1 .

Example of rfind() function in Python

Explanation:

In the above example, we are finding the index of the last occurrence of val in txt using the rfind() method in Python. The index of the last occurrence of val is found out to be 18.

What is rfind() function in Python?

The rfind() method is an inbuilt string method in Python that returns the index of the last occurrence of a substring in the given string. If the substring is not found in the given string, rfind() returns -1 .

rfind function in python

We can use the optional arguments start and end in the rfind() method to specify the start and end of the string in which we have to find the substring. The rfind() is a case sensitive method, "Scaler" and "scaler" are two different words for it.

what is rfind in python

The string rfind() method is very similar to the string rindex() method, both of them return the index of the last occurrence of a substring in the given string, the only difference between them is, when the substring is not found in the given string, the rfind() method will return -1, whereas the rindex() method will raise an error.

More Examples

Let's take a look at some more examples of the rfind() method in Python for a better understanding:

Example 1: Using rfind() with no start and end argument

Explanation:

In the above example, we are finding the index of the last occurrence of "cream" in the string "I scream you scream, we all scream ice-cream" using the rfind() method. As we can see in the given string, the substring "cream" is present at indices 3, 14, 29, and 39 . The rfind() method will return the highest index among these indices, that being 39 , so the return value will be 39 .

Example 2: Using rfind() with start and end arguments

Explanation:

In the above example, we are using the rfind() method to find the index of the last occurrence of "cream" in the string "I scream you scream, we all scream ice-cream" between the starting position - 3 and ending position - 20 . As we can see in the given string between the boundaries, the substring "cream" is present at index 14, so the return value will be 14 .

Example 3: Behaviour of rfind() and rindex() when the value is not found in the given string

Behaviour of rfind() method

Explanation:

In the above example, we are finding the index of the last occurrence of "Pizza" in the string "Fried Chicken, Fried rice, Ramen" using the rfind() method. As we can see in the given string, the substring "Pizza" is not present at any position, so the return value will be -1 .

Behaviour of rindex() method

Explanation:

In the above example, we are finding the index of the last occurrence of "Pizza" in the string "Fried Chicken, Fried rice, Ramen" using the rindex() method. As we can see in the given string, the substring "Pizza" is not present in the given string, so the rindex() method will raise a ValueError , stating that the substring is not found.

Conclusion

  • The string rfind() method returns the index of the last position of a substring in the given string and returns -1 if it is not found.
  • We can specify the starting and ending position of checking the substring in the given string using the start and end parameters.
  • The only difference between the rfind() method and rindex() method is that if the substring is not found in the given string, rfind() method returns -1, whereas rindex() raises an error.
  • The string rfind() method can also be used to check whether a substring is present in the given string or not.

See Also

Refer to these topics below:

Источник

Оцените статью