Digital Communication


Digital Communication

Python String index: determine the index of a Substring


With Python, the “index()” method allows you to perform a search at the level of a character string (String) in order to identify the index of a Python Substring (which we would translate as “substring). You can decide to perform your search on the entire Python String concerned, or on only part of it.

Python String index: syntax and operation

The syntax of the “index” method is simple to explain. You can call this method with One. Two Or three arguments, knowing that the last two are optional. The first argument necessarily corresponds to the Substring according to which the character string must be analyzed. The two optional arguments represent the indexes from which the search should be started or stopped. These should only be passed if only a certain part of the String needs to be examined based on the substring. Below is a section of code that demonstrates the syntax for this method.

string.index(substring, start, end)


In this example, “string” designates any character string, while “substring” corresponds to the substring to search for. “start” and “end” respectively indicate the start and end indexes of the search. If no ending index is specified (for a total of two arguments only), the search is simply performed to the end of the String. The method then returns the index of the first occurrence of the Substring as a return value. In this way, if a Substring appears several times, “index()” will ignore all occurrences except the first.

The example below also illustrates how the method works:

string = "Je suis une chaîne de caractères"


# Résultat : 3 (le "suis" dans "Je suis")

print(string.index("suis", 7, len(string) - 1))
# Résultat : 3 (le "suis" dans "Je suis")

print(string.index("suis", 7))
# Résultat : 3 (le "suis" dans "Je suis")

# Erreur d'exception : ValueError


As you can see in the example above, when the “index()” method is called for the second time, only the first index “am” is returned for “I am”. All other occurrences of “am” are ignored. Regarding the last call to the “index()” method, you can see that it returns a “ValueError” expression if it cannot find the substring in question. Such an exception is also thrown if you enter negative indexes, or if the “start” index is greater than the “end” index. If any of these cases could potentially occur in your program, then you should handle the exception accordingly.

Processing Strings is a mission that often comes up in Python programming. Thus, it is important to save and edit Strings in a format that is appropriate. Consult our article dedicated to Python String Format to find out how to adapt the format of your Strings according to your needs.

Another solution: the find method

Depending on your use of the index method, the find method could possibly be a wiser choice. It is almost identical to the index method, except for one detail (but this is important): if the substring in question is not identified, no exception is triggered. Instead, the method just returns the value “-1”. Since an unhandled exception could cause your program to crash, this method could be very beneficial to you if you are unable or simply don't want to handle a possible exception. . You can even simulate exception handling using an if condition, as shown in the example below:

string = "Python"

if(string.find("Py") != -1):
    print("Sous-chaîne présente ! Index : ", string.find("Py"))
    print("Sous-chaîse non présente !")


In this example, a join is possible if no Substring is found (exactly like handling an exception), the main difference being that in this example it is necessary to execute the “find()” method several times if the substring is identified.

Looking at the programming languages ​​available today, Python is among the most flexible. It therefore allows you to perform countless operations on Strings. To learn more, check out our article on the different ways to compare Strings with Python.

Python String index: examples

Now, take a look at two examples illustrating how the “index()” method can be used in a program. Let's start with a simple example before looking at another, a little more complex one.

string = "Les chaussettes de l'archiduchesse sont-elles sèches, archi-sèches ?"
print("La chaîne de caractères à vérifier est ", string)

    sub = input("Entrez la sous-chaîne : ")
        print("L‘index est : ", string.index(sub))
        print("La sous-chaîne n'est pas présente :/")


In this example, a substring is searched within a character string. The code then indicates whether the Substring appears in the String in question and, if so, at what index it is located. In such a case, the String to be analyzed is predefined, while the Substring is entered each time by the user.

def try_except(start):
        return string.index(sub, start)
        return -1

string = input("Entrez la chaîne de caractères : ")
sub = input("Entrez la chaîne de caractères : ")

occurences = 0
start = 0

while(try_except(start) != -1):
    start = try_except(start) + len(sub)
    occurences = occurences + 1

print("Occurences : ", occurences)


This example illustrates checking the occurrence or occurrences of a Substring within a character string entered by the user. If an occurrence of the substring is identified in the String, the number of occurrences is then incremented, then the search is restarted from this point. Once the end of the String is reached, the total number of occurrences is displayed and the program ends.

Are you looking for a solution to publish your web application quickly and easily? Then Deploy Now is really the IONOS platform for you!

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact