Как найти последнее вхождение в строку python

Sometimes, while working with strings, we need to find if a substring exists in the string. This problem is quite common and its solution has been discussed many times before. The variation of getting the last occurrence of the string is discussed here. Let’s discuss certain ways in which we can find the last occurrence of substring in string in Python. 

Using rindex() to find last occurrence of substring

rindex() method returns the last occurrence of the substring if present in the string. The drawback of this function is that it throws the exception if there is no substring in the string and hence breaks the code. 

Python3

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

print("The original string : " + str(test_string))

res = test_string.rindex(tar_word)

print("Index of last occurrence of substring is : " + str(res))

Output

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Using rfind() to find last occurrence of substring

rfind() is the alternate method to perform this task. The advantage that this function offers better than the above method is that, this function returns a “-1” if a substring is not found rather than throwing the error. 

Python3

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

print("The original string : " + str(test_string))

res = test_string.rfind(tar_word)

print("Index of last occurrence of substring is : " + str(res))

Output

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Using lambda() with rlocate() function

Here we are using the more_itertools library that provides us with rlocate() function that helps us to find the last occurrence of the substring in the given string.

Python3

import more_itertools as m

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

pred = lambda *x: x == tuple(tar_word)

print("The original string : " +

      str(test_string))

res = next(m.rlocate(test_string, pred=pred,

                     window_size=len(tar_word)))

print("Index of last occurrence of substring is : " +

      str(res))

Output:

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Using find() and replace() methods

Python3

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

print("The original string : " + str(test_string))

x=test_string.count(tar_word)

i=1

while(i<x):

    test_string=test_string.replace(tar_word,"*"*len(tar_word),1)

    i+=1

res=test_string.find(tar_word)

print("Index of last occurrence of substring is : " + str(res))

Output

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Time Complexity: O(n), where n is length of test_string.

Auxiliary Space: O(1)

Using the re module:

The re (regular expression) module in Python allows you to search for patterns in strings. In this approach, we use the finditer function from the re module to find all occurrences of the substring in the string. The finditer function returns an iterator yielding MatchObject instances that have information about the search, such as the start and end indices of the match.

We can then use a for loop to iterate through the matches and keep track of the index of the last occurrence by updating the last_occurrence variable whenever we find a match. Finally, we print the index of the last occurrence.

Python3

import re

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

matches = re.finditer(tar_word, test_string)

last_occurrence = -1

for match in matches:

    last_occurrence = match.start()

print("Index of last occurrence of substring is:", last_occurrence)

Output

Index of last occurrence of substring is: 28

Time complexity: O(n), where n is the length of the string
Auxiliary Space : O(n)

Using reversed() function and index()

Step-by-step approach:

  1. Reverse the test_string and tar_word
  2. Use the index() method to get the first occurrence of the reversed tar_word in the reversed test_string.
  3. Calculate the index of the last occurrence of the tar_word by subtracting the index from the length of the test_string and the length of the tar_word.

Python3

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

res = len(test_string) - test_string[::-1].index(tar_word[::-1]) - len(tar_word)

print("Index of last occurrence of substring is : " + str(res))

Output

Index of last occurrence of substring is : 28

Time complexity: O(n) where n is the length of the string
Space complexity: O(1)

Using the numpy:

Algorithm:

  1. Initialize the test string and target word.
  2. Create an empty numpy array to store the indices of all occurrences of the target word.
  3. Iterate over all possible substrings of length equal to the length of the target word in the test string. For each substring, check if it matches the target word or not. If the substring matches the target word, append the index of the first character of the substring to the numpy array.
  4. Check if any occurrences of the target word were found or not. If the numpy array is not empty, set the result to be the last element of the array (i.e., the index of the last occurrence of the target word in the test string). Otherwise, set the result to -1 (indicating that the target word was not found in the test string).
  5. Print the original string and the index of the last occurrence of the target word (or -1 if the target word was not found).

Below is the implementation of the above approach:

Python3

import numpy as np

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

indices = np.array([i for i in range(len(test_string)-len(tar_word)+1)

                    if test_string[i:i+len(tar_word)] == tar_word])

if indices.size > 0:

    res = indices[-1]

else:

    res = -1

print("The original string : " + str(test_string))

print("Index of last occurrence of substring is : " + str(res))

Output:

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Time Complexity: O(n * m), where n is the length of the test string and m is the length of the target word. This is because the list comprehension iterates over all possible substrings of length m in the test string, which takes O(n * m) time in the worst case.

Space Complexity: O(k), where k is the number of occurrences of the target word in the test string. This is because the indices of all occurrences of the target word are stored in a numpy array, which takes O(k) space. The rest of the variables used in the code take constant space.

Using rpartition() method

  • Define the string and target word to find last occurrence of substring.
  • Use the rpartition() method to split the string at the last occurrence of the target word.
  • If the length of split list is 1, print that the substring was not found in the string.
  • Otherwise, calculate the index of the last occurrence of the target word using the length of the original string, the length of the third element in the split list (which contains the characters after the last occurrence of the target word), and the length of the target word.
  • Print the index of the last occurrence of the target word.

Python3

test_string = "GfG is best for CS and also best for Learning"

tar_word = "best"

print("The original string : " + str(test_string))

split_list = test_string.rpartition(tar_word)

if len(split_list) == 1:

   print("Substring not found in string")

else:

   res = len(test_string) - len(split_list[2]) - len(tar_word)

   print("Index of last occurrence of substring is : " + str(res))

Output

The original string : GfG is best for CS and also best for Learning
Index of last occurrence of substring is : 28

Time Complexity: O(n), where n is the length of the input string.

Auxiliary Space: O(1), as no extra is used.

Last Updated :
17 Apr, 2023

Like Article

Save Article

I want to find the position (or index) of the last occurrence of a certain substring in given input string str.

For example, suppose the input string is str = 'hello' and the substring is target = 'l', then it should output 3.

How can I do this?

David B's user avatar

asked Mar 5, 2012 at 19:13

Parth Soni's user avatar

Use .rfind():

>>> s = 'hello'
>>> s.rfind('l')
3

Also don’t use str as variable name or you’ll shadow the built-in str().

answered Mar 5, 2012 at 19:15

Rik Poggi's user avatar

Rik PoggiRik Poggi

28k6 gold badges64 silver badges82 bronze badges

0

You can use rfind() or rindex()
Python2 links: rfind() rindex()

>>> s = 'Hello StackOverflow Hi everybody'

>>> print( s.rfind('H') )
20

>>> print( s.rindex('H') )
20

>>> print( s.rfind('other') )
-1

>>> print( s.rindex('other') )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

The difference is when the substring is not found, rfind() returns -1 while rindex() raises an exception ValueError (Python2 link: ValueError).

If you do not want to check the rfind() return code -1, you may prefer rindex() that will provide an understandable error message. Else you may search for minutes where the unexpected value -1 is coming from within your code…


Example: Search of last newline character

>>> txt = '''first line
... second line
... third line'''

>>> txt.rfind('n')
22

>>> txt.rindex('n')
22

answered Nov 14, 2014 at 10:51

oHo's user avatar

oHooHo

50.5k27 gold badges163 silver badges198 bronze badges

1

Use the str.rindex method.

>>> 'hello'.rindex('l')
3
>>> 'hello'.index('l')
2

answered Mar 5, 2012 at 19:15

rmmh's user avatar

rmmhrmmh

6,98125 silver badges37 bronze badges

1

Not trying to resurrect an inactive post, but since this hasn’t been posted yet…

(This is how I did it before finding this question)

s = "hello"
target = "l"
last_pos = len(s) - 1 - s[::-1].index(target)

Explanation: When you’re searching for the last occurrence, really you’re searching for the first occurrence in the reversed string. Knowing this, I did s[::-1] (which returns a reversed string), and then indexed the target from there. Then I did len(s) - 1 - the index found because we want the index in the unreversed (i.e. original) string.

Watch out, though! If target is more than one character, you probably won’t find it in the reversed string. To fix this, use last_pos = len(s) - 1 - s[::-1].index(target[::-1]), which searches for a reversed version of target.

answered Apr 7, 2018 at 14:17

Adi219's user avatar

Adi219Adi219

4,6362 gold badges20 silver badges43 bronze badges

2

Try this:

s = 'hello plombier pantin'
print (s.find('p'))
6
print (s.index('p'))
6
print (s.rindex('p'))
15
print (s.rfind('p'))

Chei's user avatar

Chei

2,1073 gold badges20 silver badges33 bronze badges

answered Oct 13, 2014 at 14:10

Gad's user avatar

GadGad

691 silver badge2 bronze badges

For this case both rfind() and rindex() string methods can be used, both will return the highest index in the string where the substring is found like below.

test_string = 'hello'
target = 'l'
print(test_string.rfind(target))
print(test_string.rindex(target))

But one thing should keep in mind while using rindex() method, rindex() method raises a ValueError [substring not found] if the target value is not found within the searched string, on the other hand rfind() will just return -1.

answered Nov 14, 2021 at 9:30

Rubel's user avatar

RubelRubel

1,20613 silver badges18 bronze badges

The more_itertools library offers tools for finding indices of all characters or all substrings.

Given

import more_itertools as mit


s = "hello"
pred = lambda x: x == "l"

Code

Characters

Now there is the rlocate tool available:

next(mit.rlocate(s, pred))
# 3

A complementary tool is locate:

list(mit.locate(s, pred))[-1]
# 3

mit.last(mit.locate(s, pred))
# 3

Substrings

There is also a window_size parameter available for locating the leading item of several items:

s = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
substring = "chuck"
pred = lambda *args: args == tuple(substring)

next(mit.rlocate(s, pred=pred, window_size=len(substring)))
# 59

answered Feb 9, 2018 at 2:23

pylang's user avatar

pylangpylang

39.7k11 gold badges127 silver badges120 bronze badges

Python String rindex() Method

Description
Python string method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists, optionally restricting the search to string[beg:end].

Syntax
Following is the syntax for rindex() method −

str.rindex(str, beg=0 end=len(string))

Parameters
str − This specifies the string to be searched.

beg − This is the starting index, by default its 0

len − This is ending index, by default its equal to the length of the string.

Return Value
This method returns last index if found otherwise raises an exception if str is not found.

Example
The following example shows the usage of rindex() method.

Live Demo

!/usr/bin/python

str1 = "this is string example....wow!!!";
str2 = "is";

print str1.rindex(str2)
print str1.index(str2)

When we run above program, it produces following result −

5
2

Ref: Python String rindex() Method
– Tutorialspoint

answered Jun 15, 2020 at 10:12

Wise4Christ's user avatar

If you don’t wanna use rfind then this will do the trick/

def find_last(s, t):
    last_pos = -1
    while True:
        pos = s.find(t, last_pos + 1)
        if pos == -1:
            return last_pos
        else:
            last_pos = pos

answered Feb 23, 2018 at 17:15

Salam's user avatar

SalamSalam

1,03114 silver badges19 bronze badges

# Last Occurrence of a Character in a String without using inbuilt functions
str = input("Enter a string : ")
char = input("Enter a character to serach in string : ")
flag = 0
count = 0
for i in range(len(str)):
    if str[i] == char:
        flag = i
if flag == 0:
    print("Entered character ",char," is not present in string")
else:
    print("Character ",char," last occurred at index : ",flag)

answered Jun 5, 2021 at 21:29

Chand's user avatar

ChandChand

111 bronze badge

you can use rindex() function to get the last occurrence of a character in string

s="hellloooloo"
b='l'
print(s.rindex(b))

taras's user avatar

taras

6,47810 gold badges39 silver badges50 bronze badges

answered Oct 7, 2019 at 10:36

praveen kumar's user avatar

str = "Hello, World"
target='l'
print(str.rfind(target) +1)

or

str = "Hello, World"
flag =0
target='l'
for i,j in enumerate(str[::-1]):
    if target == j:
       flag = 1
       break;
if flag == 1:   
    print(len(str)-i)

answered Jan 12, 2022 at 7:26

BitchBark's user avatar

Часто нам нужно найти символ в строке python. Для решения этой задачи разработчики используют метод find(). Он помогает найти индекс первого совпадения подстроки в строке. Если символ или подстрока не найдены, find возвращает -1.

Синтаксис

string.find(substring,start,end)

Метод find принимает три параметра:

  • substring (символ/подстрока) — подстрока, которую нужно найти в данной строке.
  • start (необязательный) — первый индекс, с которого нужно начинать поиск. По умолчанию значение равно 0.
  • end (необязательный) — индекс, на котором нужно закончить поиск. По умолчанию равно длине строки.

Параметры, которые передаются в метод, — это подстрока, которую требуются найти, индекс начала и конца поиска. Значение по умолчанию для начала поиска — 0, а для конца — длина строки.

В этом примере используем метод со значениями по умолчанию.

Метод find() будет искать символ и вернет положение первого совпадения. Даже если символ встречается несколько раз, то метод вернет только положение первого совпадения.


>>> string = "Добро пожаловать!"
>>> print("Индекс первой буквы 'о':", string.find("о"))
Индекс первой буквы 'о': 1

Поиск не с начала строки с аргументом start

Можно искать подстроку, указав также начальное положение поиска.

В этом примере обозначим стартовое положение значением 8 и метод начнет искать с символа с индексом 8. Последним положением будет длина строки — таким образом метод выполнит поиска с индекса 8 до окончания строки.


>>> string = "Специалисты назвали плюсы и минусы Python"
>>> print("Индекс подстроки 'али' без учета первых 8 символов:", string.find("али", 8))
Индекс подстроки 'али' без учета первых 8 символов: 16

Поиск символа в подстроке со start и end

С помощью обоих аргументов (start и end) можно ограничить поиск и не проводить его по всей строке. Найдем индексы слова «пожаловать» и повторим поиск по букве «о».


>>> string = "Добро пожаловать!"
>>> start = string.find("п")
>>> end = string.find("ь") + 1
>>> print("Индекс первой буквы 'о' в подстроке:", string.find("о", start, end))
Индекс первой буквы 'о' в подстроке: 7

Проверка есть ли символ в строке

Мы знаем, что метод find() позволяет найти индекс первого совпадения подстроки. Он возвращает -1 в том случае, если подстрока не была найдена.


>>> string = "Добро пожаловать!"
>>> print("Есть буква 'г'?", string.find("г") != -1)
Есть буква 'г'? False
>>> print("Есть буква 'т'?", string.find("т") != -1)
Есть буква 'т'? True

Поиск последнего вхождения символа в строку

Функция rfind() напоминает find(), а единое отличие в том, что она возвращает максимальный индекс. В обоих случаях же вернется -1, если подстрока не была найдена.

В следующем примере есть строка «Добро пожаловать!». Попробуем найти в ней символ «о» с помощью методов find() и rfind().


>>> string = "Добро пожаловать"
>>> print("Поиск 'о' методом find:", string.find("о"))
Поиск 'о' методом find: 1
>>> print("Поиск 'о' методом rfind:", string.rfind("о"))
Поиск 'о' методом rfind: 11

Вывод показывает, что find() возвращает индекс первого совпадения подстроки, а rfind() — последнего совпадения.

Второй способ поиска — index()

Метод index() помогает найти положение данной подстроки по аналогии с find(). Единственное отличие в том, что index() бросит исключение в том случае, если подстрока не будет найдена, а find() просто вернет -1.

Вот рабочий пример, показывающий разницу в поведении index() и find():


>>> string = "Добро пожаловать"
>>> print("Поиск 'о' методом find:", string.find("о"))
Поиск 'о' методом find: 1
>>> print("Поиск 'о' методом index:", string.index("о"))
Поиск 'о' методом index: 1

В обоих случаях возвращается одна и та же позиция. А теперь попробуем с подстрокой, которой нет в строке:


>>> string = "Добро пожаловать"
>>> print("Поиск 'г' методом find:", string.find("г"))
Поиск 'г' методом find: 1
>>> print("Поиск 'г' методом index:", string.index("г"))
Traceback (most recent call last):
File "pyshell#21", line 1, in module
print("Поиск 'г' методом index:", string.index("г"))
ValueError: substring not found

В этом примере мы пытались найти подстроку «г». Ее там нет, поэтому find() возвращает -1, а index() бросает исключение.

Поиск всех вхождений символа в строку

Чтобы найти общее количество совпадений подстроки в строке можно использовать ту же функцию find(). Пройдемся циклом while по строке и будем задействовать параметр start из метода find().

Изначально переменная start будет равна -1, что бы прибавлять 1 у каждому новому поиску и начать с 0. Внутри цикла проверяем, присутствует ли подстрока в строке с помощью метода find.

Если вернувшееся значение не равно -1, то обновляем значением count.

Вот рабочий пример:


my_string = "Добро пожаловать"
start = -1
count = 0

while True:
start = my_string.find("о", start+1)
if start == -1:
break
count += 1

print("Количество вхождений символа в строку: ", count )

Количество вхождений символа в строку:  4

Выводы

  • Метод find() помогает найти индекс первого совпадения подстроки в данной строке. Возвращает -1, если подстрока не была найдена.
  • В метод передаются три параметра: подстрока, которую нужно найти, start со значением по умолчанию равным 0 и end со значением по умолчанию равным длине строки.
  • Можно искать подстроку в данной строке, задав начальное положение, с которого следует начинать поиск.
  • С помощью параметров start и end можно ограничить зону поиска, чтобы не выполнять его по всей строке.
  • Функция rfind() повторяет возможности find(), но возвращает максимальный индекс (то есть, место последнего совпадения). В обоих случаях возвращается -1, если подстрока не была найдена.
  • index() — еще одна функция, которая возвращает положение подстроки. Отличие лишь в том, что index() бросает исключение, если подстрока не была найдена, а find() возвращает -1.
  • find() можно использовать в том числе и для поиска общего числа совпадений подстроки.

Базовые операции¶

# Конкатенация (сложение)
>>> s1 = 'spam'
>>> s2 = 'eggs'
>>> print(s1 + s2)
'spameggs'

# Дублирование строки
>>> print('spam' * 3)
spamspamspam

# Длина строки
>>> len('spam')
4

# Доступ по индексу
>>> S = 'spam'
>>> S[0]
's'
>>> S[2]
'a'
>>> S[-2]
'a'

# Срез
>>> s = 'spameggs'
>>> s[3:5]
'me'
>>> s[2:-2]
'ameg'
>>> s[:6]
'spameg'
>>> s[1:]
'pameggs'
>>> s[:]
'spameggs'

# Шаг, извлечения среза
>>> s[::-1]
'sggemaps'
>>> s[3:5:-1]
''
>>> s[2::2]
'aeg'

Другие функции и методы строк¶

# Литералы строк
S = 'str'; S = "str"; S = '''str'''; S = """str"""
# Экранированные последовательности
S = "snptanbbb"
# Неформатированные строки (подавляют экранирование)
S = r"C:tempnew"
# Строка байтов
S = b"byte"
# Конкатенация (сложение строк)
S1 + S2
# Повторение строки
S1 * 3
# Обращение по индексу
S[i]
# Извлечение среза
S[i:j:step]
# Длина строки
len(S)
# Поиск подстроки в строке. Возвращает номер первого вхождения или -1
S.find(str, [start],[end])
# Поиск подстроки в строке. Возвращает номер последнего вхождения или -1
S.rfind(str, [start],[end])
# Поиск подстроки в строке. Возвращает номер первого вхождения или вызывает ValueError
S.index(str, [start],[end])
# Поиск подстроки в строке. Возвращает номер последнего вхождения или вызывает ValueError
S.rindex(str, [start],[end])
# Замена шаблона
S.replace(шаблон, замена)
# Разбиение строки по разделителю
S.split(символ)
# Состоит ли строка из цифр
S.isdigit()
# Состоит ли строка из букв
S.isalpha()
# Состоит ли строка из цифр или букв
S.isalnum()
# Состоит ли строка из символов в нижнем регистре
S.islower()
# Состоит ли строка из символов в верхнем регистре
S.isupper()
# Состоит ли строка из неотображаемых символов (пробел, символ перевода страницы ('f'), "новая строка" ('n'), "перевод каретки" ('r'), "горизонтальная табуляция" ('t') и "вертикальная табуляция" ('v'))
S.isspace()
# Начинаются ли слова в строке с заглавной буквы
S.istitle()
# Преобразование строки к верхнему регистру
S.upper()
# Преобразование строки к нижнему регистру
S.lower()
# Начинается ли строка S с шаблона str
S.startswith(str)
# Заканчивается ли строка S шаблоном str
S.endswith(str)
# Сборка строки из списка с разделителем S
S.join(список)
# Символ в его код ASCII
ord(символ)
# Код ASCII в символ
chr(число)
# Переводит первый символ строки в верхний регистр, а все остальные в нижний
S.capitalize()
# Возвращает отцентрованную строку, по краям которой стоит символ fill (пробел по умолчанию)
S.center(width, [fill])
# Возвращает количество непересекающихся вхождений подстроки в диапазоне [начало, конец] (0 и длина строки по умолчанию)
S.count(str, [start],[end])
# Возвращает копию строки, в которой все символы табуляции заменяются одним или несколькими пробелами, в зависимости от текущего столбца. Если TabSize не указан, размер табуляции полагается равным 8 пробелам
S.expandtabs([tabsize])
# Удаление пробельных символов в начале строки
S.lstrip([chars])
# Удаление пробельных символов в конце строки
S.rstrip([chars])
# Удаление пробельных символов в начале и в конце строки
S.strip([chars])
# Возвращает кортеж, содержащий часть перед первым шаблоном, сам шаблон, и часть после шаблона. Если шаблон не найден, возвращается кортеж, содержащий саму строку, а затем две пустых строки
S.partition(шаблон)
# Возвращает кортеж, содержащий часть перед последним шаблоном, сам шаблон, и часть после шаблона. Если шаблон не найден, возвращается кортеж, содержащий две пустых строки, а затем саму строку
S.rpartition(sep)
# Переводит символы нижнего регистра в верхний, а верхнего – в нижний
S.swapcase()
# Первую букву каждого слова переводит в верхний регистр, а все остальные в нижний
S.title()
# Делает длину строки не меньшей width, по необходимости заполняя первые символы нулями
S.zfill(width)
# Делает длину строки не меньшей width, по необходимости заполняя последние символы символом fillchar
S.ljust(width, fillchar=" ")
# Делает длину строки не меньшей width, по необходимости заполняя первые символы символом fillchar
S.rjust(width, fillchar=" ")

Форматирование строк¶

S.format(*args, **kwargs)

Примеры¶

Python: Определение позиции подстроки (функции str.find и str.rfind)¶

Определение позиции подстроки в строке с помощью функций str.find и str.rfind.

In [1]: str = 'ftp://dl.dropbox.com/u/7334460/Magick_py/py_magick.pdf'

Функция str.find показывает первое вхождение подстроки. Все позиции возвращаются относительно начало строки.

In [2]: str.find('/')
Out[2]: 4

In [3]: str[4]
Out[3]: '/'

Можно определить вхождение в срезе. первое число показывает начало среза, в котором производится поиск. Второе число — конец среза. В случае отсутствия вхождения подстроки выводится -1.

In [4]: str.find('/', 8, 18)
Out[4]: -1

In [5]: str[8:18]
Out[5]: '.dropbox.c'

In [6]: str.find('/', 8, 22)
Out[6]: 20

In [7]: str[8:22]
Out[7]: '.dropbox.com/u'

In [8]: str[20]
Out[8]: '/'

Функция str.rfind осуществляет поиск с конца строки, но возвращает позицию подстроки относительно начала строки.

In [9]: str.rfind('/')
Out[9]: 40

In [10]: str[40]
Out[10]: '/'

Python: Извлекаем имя файла из URL¶

Понадобилось мне отрезать от URL всё, что находится после последнего слэша, т.е.названия файла. URL можеть быть какой угодно. Знаю, что задачу запросто можно решить с помощью специального модуля, но я хотел избежать этого. Есть, как минимум, два способа справиться с поставленным вопросом.

Способ №1¶

Достаточно простой способ. Разбиваем строку по слэшам с помощью функции split(), которая возвращает список. А затем из этого списка извлекаем последний элемент. Он и будет названием файла.

In [1]: str = 'http://dl.dropbox.com/u/7334460/Magick_py/py_magick.pdf'

In [2]: str.split('/')
Out[2]: ['http:', '', 'dl.dropbox.com', 'u', '7334460', 'Magick_py', 'py_magick.pdf']

Повторим шаг с присвоением переменной:

In [3]: file_name = str.split('/')[-1]

In [4]: file_name
Out[4]: 'py_magick.pdf'

Способ №2¶

Второй способ интереснее. Сначала с помощью функции rfind() находим первое вхождение с конца искомой подстроки. Функция возвращает позицию подстроки относительно начала строки. А далее просто делаем срез.

In [5]: str = 'http://dl.dropbox.com/u/7334460/Magick_py/py_magick.pdf'

In [6]: str.rfind('/')
Out[6]: 41

Делаем срез:

In [7]: file_name = str[42:]

In [8]: file_name
Out[8]: 'py_magick.pdf'

В этом посте мы обсудим, как найти индекс последнего вхождения символа в строку в Python.

1. Использование rfind() функция

Простое решение для поиска последнего индекса символа в строке — использование rfind() функция, которая возвращает индекс последнего вхождения в строку, где найден символ, и возвращает -1 в противном случае.

if __name__ == ‘__main__’:

    s = “Hello, World”

    c = ‘o’

    index = s.rfind(c)

    if index != 1:

        print(f“Char ‘{c}’ is found at index {index}”)    # Char ‘o’ находится в индексе 8

    else:

        print(“Char not found”)

Скачать  Выполнить код

2. Использование rindex() функция

В качестве альтернативы вы можете использовать rindex() функция, которая отличается от rfind() функционировать как rfind() возвращается -1 пока rindex() вызывает исключение ValueError когда персонаж не найден.

if __name__ == ‘__main__’:

    s = “Hello, World”

    c = ‘o’

    try:

        index = s.rindex(c)

        print(f“Char ‘{c}’ is found at index {index}”)  # Char ‘o’ находится в индексе 8

    except:

        print(“Char not found”)

Скачать  Выполнить код

Наконец, вы можете использовать more_itertools.rlocate() Функция для поиска определенных символов в строке. Он дает индекс каждого символа в строке, для которого выполняется указанный предикат.

import more_itertools

if __name__ == ‘__main__’:

    s = “Hello, World”

    c = ‘o’

    index = next(more_itertools.rlocate(s, lambda x: x == c))

    if index != 1:

        print(f“Char ‘{c}’ is found at index {index}”)    # Char ‘o’ находится в индексе 8

    else:

        print(“Char not found”)

Скачать код

Вот и все, что касается поиска индекса последнего вхождения символа в строку в Python.

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Добавить комментарий