Méthode Python String index()
Python Index de chaîne() La méthode permet à un utilisateur de trouver l'index de la première occurrence d'une sous-chaîne existante à l'intérieur d'une chaîne donnée dans Python .
Syntaxe de la méthode Python String Index()
Syntaxe: string_obj.index(sous-chaîne, début, fin)
Paramètres:
- sous-chaîne : La chaîne à rechercher.
- start (par défaut : 0) : Cette fonction précise la position à partir de laquelle la recherche doit être lancée.
- fin (par défaut : longueur de la chaîne) : Cette fonction précise la position à partir de laquelle la recherche doit se terminer.
Retour: Renvoie la première position de la sous-chaîne trouvée.
Exception: Lève ValueError si la chaîne d'argument n'est pas trouvée ou si l'index est hors plage.
Exemple de méthode Python String Index()
Ici, le premier caractère de « et » dans la chaîne aléatoire est « a » et l'indice de « a » est 1, donc la sortie est également 1.
Python3
string> => 'random'> print> (> 'index of 'and' in string:'> , string.index(> 'and'> ))> |
Sortir
Index of ' and ' in string: 1
Méthode Python String Index() pour trouver l'index d'un seul caractère
L'utilisation de base de la méthode Python string index() concerne la position d'index d'un caractère particulier ou il peut s'agir d'un mot. Ainsi, chaque fois que nous avons besoin de trouver l'index d'un caractère particulier, nous utilisons le méthode d'indexation pour l'obtenir.
Python3
# initializing target string> ch> => 'geeksforgeeks'> > # initializing argument string> ch1> => 'geeks'> > # using index() to find position of 'geeks'> # starting from 2nd index> # prints 8> pos> => ch.index(ch1,> 2> )> > print> (> 'The first position of geeks after 2nd index : '> ,end> => '')> print> (pos)> |
Sortir
The first position of geeks after 2nd index : 8
Note: La méthode index() est similaire à trouver() . La seule différence est que find() renvoie -1 si la chaîne recherchée n'est pas trouvée et que index() lève une exception dans ce cas.
Python String Index() avec arguments de début et de fin
Le index()> méthode en Python est utilisé pour trouver l'index de la première occurrence d'une sous-chaîne dans une chaîne. Il renvoie l'index de la sous-chaîne si elle est trouvée et lève un ValueError> si la sous-chaîne n'est pas présente.
Python3
test_string> => '1234gfg4321'> # finding gfg in string segment 'gfg4'> print> (test_string.index(> 'gfg'> ,> 4> ,> 8> ))> > # finding '21' in string segment 'gfg4321'> print> (test_string.index(> '21'> ,> 8> ,> len> (test_string)))> > # finding '32' in string segment 'fg432' using negative index> print> (test_string.index(> '32'> ,> 5> ,> -> 1> ))> |
Sortir
4 9 8
Méthode Python String Index() utilisant la compréhension de liste
Le index()> méthode en Python est utilisé pour trouver l'index de la première occurrence d'une sous-chaîne dans une chaîne. Cet exemple utilise la compréhension de liste pour rechercher les indices de plusieurs sous-chaînes dans la chaîne.
Python3
text> => 'Hello Geeks and welcome to Geeksforgeeks'> substring_list> => [> 'Geeks'> ,> 'welcome'> ,> 'notfound'> ]> > indices> => [text.index(sub)> if> sub> in> text> else> -> 1> for> sub> in> substring_list]> print> (indices)> |
Sortir
[6, 16, -1]
Méthode Python String Index() utilisant Tuple
Le index()> méthode en Python est utilisé pour trouver l'index de la première occurrence d'une sous-chaîne dans une chaîne. La méthode index() peut être utilisée avec un tuple pour trouver l'index de la première occurrence de n'importe quelle sous-chaîne du tuple dans la chaîne donnée.
Python3
text> => 'Hello Geeks! and welcome to Geeksforgeeks'> substring_tuple> => (> 'Geeks'> ,> 'to'> ,> '!'> ,> 'notfound'> )> > for> sub> in> substring_tuple:> > try> :> > index> => text.index(sub)> > print> (f> 'Index of '{sub}': {index}'> )> > except> ValueError as e:> > print> (f> 'Substring '{sub}' not found!'> )> |
Sortir
Index of 'Geeks': 6 Index of 'to': 25 Index of '!': 11 Substring 'notfound' not found!
Exception lors de l'utilisation de la méthode Python String index()
Parfois, nous avons des exceptions qui conduisent à une erreur dans le cas de index(), nous avons ici une erreur également nommée Value Error.
Erreur de valeur : Cette erreur est générée dans le cas où la chaîne d'argument n'est pas trouvée dans la chaîne cible.
Python
# initializing target string> ch> => 'geeksforgeeks'> > # initializing argument string> ch1> => 'gfg'> > # using index() to find position of 'gfg'> # raises error> pos> => ch.index(ch1)> > print> (> 'The first position of gfg is : '> ,end> => '')> print> (pos)> |
Sortir
Traceback (most recent call last): File '/home/aa5904420c1c3aa072ede56ead7e26ab.py', line 12, in pos = ch.index(ch1) ValueError: substring not found
Application pratique
Python La fonction de méthode String index() est utilisée pour extraire le longueur du suffixe ou du préfixe après ou avant le mot cible . L'exemple ci-dessous affiche la longueur totale en bits d'une instruction provenant d'une tension alternative à partir d'informations dans un format chaîne .
Python
# initializing target strings> VOLTAGES> => [> '001101 AC'> ,> '0011100 DC'> ,> '0011100 AC'> ,> '001 DC'> ]> > # initializing argument string> TYPE> => 'AC'> > # initializing bit-length calculator> SUM_BITS> => 0> > for> i> in> VOLTAGES:> > > ch> => i> > > if> ch[> len> (ch)> -> 2> ] !> => 'D'> :> > # extracts the length of bits in string> > bit_len> => ch.index(> TYPE> )> -> 1> > > # adds to total> > SUM_BITS> => SUM_BITS> +> bit_len> > print> (> 'The total bit length of AC is : '> , SUM_BITS)> |
Sortir
The total bit length of AC is : 13