Python find all indexes in string

Методы 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'))

Источник

Python find all indexes in string

Last updated: Feb 22, 2023
Reading time · 5 min

banner

# Table of Contents

# Find all indexes of a substring using startswith()

To find all indexes of a substring in a string:

  1. Use a list comprehension to iterate over a range object of the string's length.
  2. Check if each character starts with the given substring and return the result.
Copied!
string = 'bobby hadz bobbyhadz.com' indexes = [ index for index in range(len(string)) if string.startswith('bobby', index) ] print(indexes) # 👉️ [0, 11]

We used a range object to iterate over the string.

Copied!
string = 'bobby hadz bobbyhadz.com' # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, # 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] print(list(range(len(string))))

find all indexes of substring using startswith

The range class is commonly used for looping a specific number of times in for loops and takes the following arguments:

Name Description
start An integer representing the start of the range (defaults to 0 )
stop Go up to, but not including the provided integer
step Range will consist of every N numbers from start to stop (defaults to 1 )

If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.

Copied!
for n in range(5): print(n) # 👉️ 0 1 2 3 4 result = list(range(5)) # 👇️ [0, 1, 2, 3, 4] print(result)

On each iteration, we check if the slice of the string that starts at the current character starts with the given substring.

Copied!
string = 'bobby hadz bobbyhadz.com' indexes = [ index for index in range(len(string)) if string.startswith('bobby', index) ] print(indexes) # 👉️ [0, 11]

If the condition is met, the corresponding index is returned.

Читайте также:  Recording demos in css

The new list contains all of the indexes of the substring in the string.

# Find all indexes of a substring in a String using re.finditer()

This is a three-step process:

  1. Use the re.finditer() to get an iterator object of the matches.
  2. Use a list comprehension to iterate over the iterator.
  3. Use the match.start() method to get the indexes of the substring in the string.
Copied!
import re string = 'bobby hadz bobbyhadz.com' indexes = [ match.start() for match in re.finditer(r'bob', string) ] print(indexes) # 👉️ [0, 11]

find all indexes of substring using re finditer

The re.finditer() method takes a regular expression and a string and returns an iterator object containing the matches for the pattern in the string.

Copied!
import re string = 'bobby hadz bobbyhadz.com' # 👇️ [, # ] print(list( re.finditer(r'bob', string) ))

The match.start() method returns the index of the first character of the match.

Copied!
import re string = 'bobby hadz bobbyhadz.com' print( list(re.finditer(r'bob', string))[0].start() # 👉️ 0 ) print( list(re.finditer(r'bob', string))[1].start() # 👉️ 11 )

The new list contains the index of all occurrences of the substring in the string.

Copied!
import re string = 'bobby hadz bobbyhadz.com' indexes = [ match.start() for match in re.finditer(r'bob', string) ] print(indexes) # 👉️ [0, 11]

Alternatively, you can use a for loop.

# Find all indexes of a substring in a String using a for loop

This is a four-step process:

  1. Declare a new variable that stores an empty list.
  2. Use the re.finditer() to get an iterator object of the matches.
  3. Use a for loop to iterate over the object.
  4. Append the index of each match to the list.
Copied!
import re string = 'bobby hadz bobbyhadz.com' indexes = [] for match in re.finditer(r'bob', string): indexes.append(match.start()) print(indexes) # 👉️ [0, 11]

We used a for loop to iterate over the iterator object.

On each iteration, we use the match.start() method to get the index of the current match and append the result to the indexes list.

The list.append() method adds an item to the end of the list.

# Find all indexes of a substring using a while loop

You can also use a while loop to find all indexes of a substring in a string.

Copied!
def find_indexes(a_string, substring): start = 0 indexes = [] while start len(a_string): start = a_string.find(substring, start) if start == -1: return indexes indexes.append(start) start += 1 return indexes string = 'bobby hadz bobbyhadz.com' print(find_indexes(string, 'bob')) # 👉️ [0, 11] string = 'bobobobob' print(find_indexes(string, 'bob')) # 👉️ [0, 2, 4, 6]

The find_indexes substring takes a string and a substring and returns a list containing all of the indexes of the substring in the string.

We used a while loop to iterate for as long as the start variable is less than the string's length.

On each iteration, we use the str.find() method to find the next index of the substring in the string.

The str.find method returns the index of the first occurrence of the provided substring in the string.

The method returns -1 if the substring is not found in the string.

If the substring is not found in the string -1 is returned and we return the indexes list.

Otherwise, we add the index of the occurrence to the list and increment the start variable by 1 .

Notice that the function in the example finds indexes of overlapping substrings as well.

Copied!
def find_indexes(a_string, substring): start = 0 indexes = [] while start len(a_string): start = a_string.find(substring, start) if start == -1: return indexes indexes.append(start) start += 1 return indexes string = 'bobobobob' print(find_indexes(string, 'bob')) # 👉️ [0, 2, 4, 6]

# Finding only non-overlapping results

If you need to only find the indexes of the non-overlapping substrings, add the length of the substring to the start variable.

Copied!
def find_indexes(a_string, substring): start = 0 indexes = [] while start len(a_string): start = a_string.find(substring, start) if start == -1: return indexes indexes.append(start) start += len(substring) # 👈️ only non-overlapping return indexes string = 'bobobobob' print(find_indexes(string, 'bob')) # 👉️ [0, 4]

Instead of adding 1 to the start variable when iterating, we added the length of the substring to only get the indexes of the non-overlapping matches.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Find All Indexes of a Character in Python String

Find All Indexes of a Character in Python String

  1. Find All Indexes of a Character Inside a String With Regular Expressions in Python
  2. Find All Indexes of a Character Inside a String With the yield Keyword in Python
  3. Find All Indexes of a Character Inside a String With List Comprehensions in Python

This tutorial will discuss the methods to get all the indexes of a character inside a string in Python.

Find All Indexes of a Character Inside a String With Regular Expressions in Python

We can use the finditer() function inside the re module of Python for our specific problem. The finditer() function takes the pattern and the string as input parameters. It reads the string from left to right and returns all the indexes where the pattern occurs. We can use this function with list comprehensions to store the result inside a list in Python. The following code snippet shows us how to find all indexes of a character inside a string with regular expressions.

import re string = "This is a string" char = "i" indices = [i.start() for i in re.finditer(char, string)] print(indices) 

We used the re.finditer() function to iterate through each character inside the string and find all the characters that matched char . We returned the index i.start() of all the characters that matched char in the form of a list and stored them inside indices . In the end, we displayed all the elements of indices .

Find All Indexes of a Character Inside a String With the yield Keyword in Python

We can also use the yield keyword inside a function to solve our specific problem. The yield keyword is used to return multiple values from a function without destroying the state of the local variables of that function. When the function is called again, the execution starts from the previous yield statement. We can use this keyword to return all the instances of a character inside a string. The following code example shows us how to find all the indexes of a character inside a string with the yield keyword.

def find(string, char):  for i, c in enumerate(string):  if c == char:  yield i  string = "This is a string" char = "i" indices = list(find(string, char)) print(indices) 

We defined the find(string, char) function that iterates through each character inside the string and yields the index i if the character matches char . While calling the find() function, we stored all the returned values inside a list and displayed all the elements of the list.

Find All Indexes of a Character Inside a String With List Comprehensions in Python

We can also use list comprehensions to solve our problem. List comprehensions are used to create new lists based on previously existing lists. We can use list comprehensions to iterate through each character inside the string variable and return the index if the character matches the desired character. List comprehensions return values in the form of lists. We can store these index values inside a list and display the results. The following code snippet shows us how to find all indexes of a character inside a string with list comprehensions.

string = "This is a string" char = "i" indices = [i for i, c in enumerate(string) if c == char] print(indices) 

We used list comprehensions to iterate through each character c inside the string variable and returned its index i if the character c is equal to our desired character char . This is the simplest and the easiest way to find all the indexes of a character inside a string.

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Related Article - Python String

Источник

Python find all indexes of character in a string | Example code

You don’t need to use a special method to find all indexes of characters in a string in Python. Just use for-loop and if statement logic to get done this task.

Python find all indexes of character in a string Example

Simple example code finds all occurrence index of “s” char in a given string.

text = 'Python is easy programing language' s = 's' res = [] for i in range(len(text)): if text[i] == s: res.append(i) print(res) 

Python find all indexes of character in a string

How to find char in string and get all the indexes?

Here is another approach using enumerate to get a list of all indexes of char.

text = 'Python is easy programing language' def find(s, ch): return [i for i, ltr in enumerate(s) if ltr == ch] print(find(text, 's')) 

Output: [8, 12]

Do comment if you have any doubts and suggestions on this Python char index topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Источник

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