Python 문자열 index() 메서드

파이썬 문자열 인덱스() 이 방법을 사용하면 사용자는 주어진 문자열 내에서 기존 하위 문자열이 처음 나타나는 인덱스를 찾을 수 있습니다. 파이썬 .

Python 문자열 인덱스() 메서드 구문

통사론: string_obj.index(하위 문자열, 시작, 끝)

매개변수:

  • 하위 문자열: 검색할 문자열입니다.
  • 시작 (기본값 : 0) : 검색을 시작해야 하는 위치를 지정하는 기능입니다.
  • end (기본값: 문자열 길이): 검색이 종료되어야 하는 위치를 지정하는 기능입니다.

반품: 발견된 하위 문자열의 첫 번째 위치를 반환합니다.

예외: 인수 문자열을 찾을 수 없거나 인덱스가 범위를 벗어나면 ValueError가 발생합니다.

Python 문자열 인덱스() 메서드 예

여기서 문자열 무작위의 'and'의 첫 번째 문자는 'a'이고 'a'의 인덱스는 1이므로 출력도 1입니다.

파이썬3




string> => 'random'> print> (> 'index of 'and' in string:'> , string.index(> 'and'> ))>

산출

Index of '  and  ' in string: 1 

단일 문자의 인덱스를 찾는 Python String Index() 방법

Python 문자열 index() 메서드의 기본 사용법은 특정 문자의 인덱스 위치이거나 단어일 수 있습니다. 따라서 특정 문자의 색인을 찾아야 할 때마다 다음을 사용합니다. 인덱스 방법 그것을 얻기 위해.

파이썬3




# 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)>

산출

The first position of geeks after 2nd index : 8 

메모: index() 메소드는 다음과 유사합니다. 찾다() . 유일한 차이점은 검색된 문자열을 찾을 수 없으면 find()는 -1을 반환하고 이 경우 index()는 예외를 발생시킨다는 것입니다.

시작 및 끝 인수가 있는 Python 문자열 인덱스()

그만큼 index()> Python의 메소드 문자열 내에서 부분 문자열이 처음 나타나는 인덱스를 찾는 데 사용됩니다. 발견된 경우 하위 문자열의 인덱스를 반환하고 ValueError> 하위 문자열이 존재하지 않는 경우.

파이썬3




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> ))>

산출

4 9 8 

List Comprehension을 사용하는 Python String Index() 메서드

그만큼 index()> Python의 메소드 문자열 내에서 부분 문자열이 처음 나타나는 인덱스를 찾는 데 사용됩니다. 이 예에서는 목록 이해를 사용하여 문자열에서 여러 하위 문자열의 인덱스를 찾습니다.

파이썬3




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)>

산출

[6, 16, -1] 

Tuple을 사용하는 Python String Index() 메서드

그만큼 index()> Python의 메소드 문자열 내에서 부분 문자열이 처음 나타나는 인덱스를 찾는 데 사용됩니다. index() 메서드를 튜플과 함께 사용하면 주어진 문자열 내의 튜플에서 하위 문자열이 처음 나타나는 인덱스를 찾을 수 있습니다.

파이썬3




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!'> )>

산출

Index of 'Geeks': 6 Index of 'to': 25 Index of '!': 11 Substring 'notfound' not found! 

Python String index() 메서드를 사용할 때 예외

때로는 index()의 경우 일부 오류로 이어지는 몇 가지 예외가 발생합니다. 여기에는 Value Error라는 오류도 있습니다.

값오류: 이 오류는 인수 문자열이 대상 문자열에서 발견되지 않는 경우 발생합니다.

파이썬




# 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)>

산출

Traceback (most recent call last):  File '/home/aa5904420c1c3aa072ede56ead7e26ab.py', line 12, in   pos = ch.index(ch1) ValueError: substring not found 

실용적인 응용 프로그램

파이썬 문자열 index() 메서드 함수는 문자열을 추출하는 데 사용됩니다. 대상 단어 뒤 또는 앞의 접미사 또는 접두사 길이 . 아래 예는 AC 전압에서 나오는 명령의 총 비트 길이를 표시합니다. .

파이썬




# 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)>

산출

The total bit length of AC is : 13