Python string index last

Python: Find an Index (or all) of a Substring in a String

Python Find All Indexes of Substring in String Cover Image

In this post, you’ll learn how to find an index of a substring in a string, whether it’s the first substring or the last substring. You’ll also learn how to find every index of a substring in a string.

Knowing how to work with strings is an important skill in your Python journey. You’ll learn how to create a list of all the index positions where that substring occurs.

The Quick Answer:

Quick Answer - Find All Indices of a Substring in a Python String

How to Use Python to Find the First Index of a Substring in a String

If all you want to do is first index of a substring in a Python string, you can do this easily with the str.index() method. This method comes built into Python, so there’s no need to import any packages.

Читайте также:  Паттерн регулярных выражений php

Let’s take a look at how you can use Python to find the first index of a substring in a string:

a_string = "the quick brown fox jumps over the lazy dog. the quick brown fox jumps over the lazy dog" # Find the first index of 'the' index = a_string.index('the') print(index) # Returns: 0

We can see here that the .index() method takes the parameter of the sub-string that we’re looking for. When we apply the method to our string a_string , the result of that returns 0 . This means that the substring begins at index position 0, of our string (i.e., it’s the first word).

Let’s take a look at how you can find the last index of a substring in a Python string.

How to Use Python to Find the Last Index of a Substring in a String

There may be many times when you want to find the last index of a substring in a Python string. To accomplish this, we cannot use the .index() string method. However, Python comes built in with a string method that searches right to left, meaning it’ll return the furthest right index. This is the .rindex() method.

Let’s see how we can use the str.rindex() method to find the last index of a substring in Python:

a_string = "the quick brown fox jumps over the lazy dog. the quick brown fox jumps over the lazy dog" # Find the last index of 'the' index = a_string.rindex('the') print(index) # Returns: 76

In the example above, we applied the .rindex() method to the string to return the last index’s position of our substring.

How to Use Regular Expression (Regex) finditer to Find All Indices of a Substring in a Python String

The above examples both returned different indices, but both only returned a single index. There may be other times when you may want to return all indices of a substring in a Python string.

For this, we’ll use the popular regular expression library, re . In particular, we’ll use the finditer method, which helps you find an iteration.

Let’s see how we can use regular expressions to find all indices of a substring in a Python string:

import re a_string = "the quick brown fox jumps over the lazy dog. the quick brown fox jumps over the lazy dog" # Find all indices of 'the' indices_object = re.finditer(pattern='the', string=a_string) indices = [index.start() for index in indices_object] print(indices) # Returns: [0, 31, 45, 76]

This example has a few more moving parts. Let’s break down what we’ve done step by step:

  1. We imported re and set up our variable a_string just as before
  2. We then use re.finditer to create an iterable object containing all the matches
  3. We then created a list comprehension to find the .start() value, meaning the starting index position of each match, within that
  4. Finally, we printed our list of index start positions

In the next section, you’ll learn how to use a list comprehension in Python to find all indices of a substring in a string.

How to Use a Python List Comprehension to Find All Indices of a Substring in a String

Let’s take a look at how you can find all indices of a substring in a string in Python without using the regular expression library. We’ll accomplish this by using a list comprehension.

Want to learn more about Python list comprehensions? Check out my in-depth tutorial about Python list comprehensions here, which will teach you all you need to know!

Let’s see how we can accomplish this using a list comprehension:

a_string = "the quick brown fox jumps over the lazy dog. the quick brown fox jumps over the lazy dog" # Find all indices of 'the' indices = [index for index in range(len(a_string)) if a_string.startswith('the', index)] print(indices) # Returns: [0, 31, 45, 76]

Let’s take a look at how this list comprehension works:

  1. We iterate over the numbers from 0 through the length of the list
  2. We include the index position of that number if the substring that’s created by splitting our string from that index onwards, begins with our letter
  3. We get a list returned of all the instances where that substring occurs in our string

In the final section of this tutorial, you’ll learn how to build a custom function to return the indices of all substrings in our Python string.

How to Build a Custom Function to Find All Indices of a Substring in a String in Python

Now that you’ve learned two different methods to return all indices of a substring in Python string, let’s learn how we can turn this into a custom Python function.

Why would we want to do this? Neither of the methods demonstrated above are really immediately clear a reader what they accomplish. This is where a function would come in handy, since it allows a future reader (who may, very well, be you!) know what your code is doing.

# Create a custom function to return the indices of all substrings in a Python string a_string = "the quick brown fox jumps over the lazy dog. the quick brown fox jumps over the lazy dog" def find_indices_of_substring(full_string, sub_string): return [index for index in range(len(full_string)) if full_string.startswith(sub_string, index)] indices = find_indices_of_substring(a_string, 'the') print(indices) # Returns: [0, 31, 45, 76]

In this sample custom function, we use used our list comprehension method of finding the indices of all substrings. The reason for this is that it does not create any additional dependencies.

Conclusion

In this post, you leaned how to use Python to find the first index, the last index, and all indices of a substring in a string. You learned how to do this with regular string methods, with regular expressions, list comprehensions, as well as a custom built function.

To learn more about the re.finditer() method, check out the official documentation here.

Источник

Python – Get Last Index of Character in String

In this tutorial, we will look at how to get the last index of a character in a Python string with the help of some examples.

last index of character

A character may appear multiple times in a string. For example, in the string “banana”, the character “a” occurs three times – at indexes 1, 3, and 5 respectively. We are looking for a way to get its last index. For example, 5 in this case.

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Note that, characters in a string are indexed starting from 0 in Python.

How to get the last index of a character in a string?

There are built-in string functions in Python like find() and index() to get the index of the first occurrence of a character but there isn’t one for getting the index of its last occurrence.

To get the last index of a character in a string in Python, subtract its first index in the reversed string and one from the length of the string.

Let’s look at a couple of ways to perform the above operation with the help of some examples.

Using string slice with a -1 step size

To get the last index of a character in the string –

  1. Reverse the string using the slice operation with a -1 step size. For example, for string s , s[::-1] will give the reversed string.
  2. Find the first index of the character in the reversed string using the string index() function.
  3. Subtract the above index and 1 from the length of the string to get the last index of the character in the original string.
# create a string s = "banana" # reverse the string rev_s = s[::-1] # get last index of the req. character print(len(s) - rev_s.index("a") - 1)

You can see that we get the last index of “a” in “banana” as 5.

Using the reversed() function

To get the last index of a character in the string –

  1. Use the Python built-in reversed() function to get the list of characters in the string in the reveresd order and then using the stirng join() function to join them together in a string. This will give you the reversed string.
  2. Find the first index of the character in the reversed string using the string index() function.
  3. Subtract the above index and 1 from the length of the string to get the last index of the character in the original string.
# create a string s = "banana" # reverse the string rev_s = "".join(reversed(s)) # get last index of the req. character print(len(s) - rev_s.index("a") - 1)

We get the same result as above.

For more on the reversed() function, refer to its documentation.

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

How to find index of last occurrence of a substring in a string in Python?

A string is a collection of characters that can represent a single word or a whole sentence. We can declare a string or any other datatype in python without the datatype specifier. Therefore, it is easy to use strings in Python compared to Java.

A string is an object of the String class, which contains multiple methods to manipulate and access strings.

In this article, we are going to focus on how to find index of last occurrence of a substring in a string in Python.

Using the rindex() method

One way to find the index of last occurrence of a substring is using the rindex() method from the inbuilt python String class. It accepts a string representing the substring to be found as a parameter, and returns the last index of the given string in the current one.

The main drawback of this function is that it throws an exception if there is no substring present in the string.

To overcome the drawback of rindex(), there is another function named rfind(). Its functionality is similar to that of rindex(), but this method does not return an exception if the given substring is not present in the string, instead, it returns ‘ 1’ indicating that the given substring is not present.

Both rindex() and rfind() have optional parameters where you can mention the start index from where you would want to start and the end index

Example 1

In the example given below, we are using the method rindex() to find out the last occurrence of the character ‘t’ in the given string.

str1 = "Welcome to tutorialspoint" index = str1.rindex('t') print("The last index of t in the given string is",index)

Output

The output of the above given example is,

('The last index of t in the given string is', 24)

Example 2

In the example given below, we are trying to find out the last index of the character ‘d’ in the given string using rindex() method, but the character ‘d’ is not present in the string.

str1 = "Welcome to tutorialspoint" index = str1.rindex('d') print("The last index of t in the given string is",index)

Output

The output of the above given example is,

Traceback (most recent call last): File "main.py", line 3, in index = str1.rindex('d') ValueError: substring not found 

Example 3

In the example given below, we are using the method rfind() to find out the last occurrence of the character ‘t’ in the given string.

str1 = "Welcome to tutorialspoint" index = str1.rfind('t') print("The last index of t in the given string is",index)

Output

The output of the above given example is,

('The last index of t in the given string is', 24)

Example 4

In the example given below, we are trying to find out the last index of the character ‘d’ in the given string using the rfind() method, but the character ‘d’ is not present in the string.

str1 = "Welcome to tutorialspoint" index = str1.rfind('d') print("The last index of t in the given string is",index)

Output

The output of the above example is,

('The last index of t in the given string is', -1)

Источник

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