산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

Python String.find() 메서드 마스터하기: 문법, 예제, 대안 비교

Python String.find()란?

String.find() 메서드는 지정된 부분문자열이 문자열에서 처음 나타나는 인덱스 반환. 부분문자열 없으면 예외 대신 -1 우아하게 반환해 부분문자열 검색에 편리한 선택.

이 가이드에서 find() 효과적 사용법, 매개변수 탐구, 관련 메서드 비교, 부분문자열 출현 횟수 세기까지 배웁니다.

Python string find() 문법

메서드 시그니처는 직관적:

string.find(substring, start, end)

매개변수

기본값으로 find() 사용

start, end 제공 안 하면 find()는 문자열 처음부터 끝까지 스캔. 첫 매칭 인덱스 반환, 없으면 -1.

예제:

mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials is at:", mystring.find("Tutorials"))

출력:

The position of Tutorials is at: 12

시작 인덱스 지정

start 인수 제공하면 해당 위치부터 문자열 끝까지 검색 제한.

예제:

mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials is at:", mystring.find("Tutorials", 20))

출력:

The position of Tutorials is at 48

시작과 끝 범위 정의

start, end 둘 다 제공하면 문자열 특정 슬라이스로 검색 한정.

예제:

mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials is at:", mystring.find("Tutorials", 5, 30))

출력:

The position of Tutorials is at 12

위치 찾기와 없는 부분문자열 처리

find() 동작: 부분문자열 있을 때와 없을 때.

예제:

mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Best site is at:", mystring.find("Best site", 5, 40))
print("The position of Guru99 is at:", mystring.find("Guru99", 20))

출력:

The position of Best site is at: 27
The position of Guru99 is at: -1

rfind()와 비교

rfind()는 find()와 유사하지만 부분문자열 발생하는 가장 높은 인덱스 반환. 부분문자열 없으면 둘 다 -1 반환.

예제:

mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials using find() : ", mystring.find("Tutorials"))
print("The position of Tutorials using rfind() : ", mystring.rfind("Tutorials"))

출력:

The position of Tutorials using find() : 12
The position of Tutorials using rfind() : 48

index()와 비교

index() 메서드는 find()처럼 동작하지만 부분문자열 없을 때 ValueError 발생.

예제:

mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials using find() : ", mystring.find("Tutorials"))
print("The position of Tutorials using index() : ", mystring.index("Tutorials"))

출력:

The position of Tutorials using find() : 12
The position of Tutorials using index() : 12

부분문자열 없을 때:

mystring = "Meet Guru99 Tutorials Site.Best site for Python Tutorials!"
print("The position of Tutorials using find() : ", mystring.find("test"))
print("The position of Tutorials using index() : ", mystring.index("test"))

출력:

The position of Tutorials using find() : -1
Traceback (most recent call last):
File "task1.py", line 3, in 
print("The position of Tutorials using index() : ", mystring.index("test"))
ValueError: substring not found

부분문자열 발생 횟수 세기

부분문자열 등장 횟수 세려면 문자열 순회하며 find()를 업데이트된 시작 인덱스로 반복 호출.

예제:

my_string = "test string test, test string testing, test string test string"
startIndex = 0
count = 0
for _ in range(len(my_string)):
    k = my_string.find('test', startIndex)
    if k != -1:
        startIndex = k + 1
        count += 1
print("The total count of substring test is:", count)

출력:

The total count of substring test is: 6

핵심 요약

python

  1. Java String length() 메서드: 문자열 크기 구하기 (예제 포함)
  2. Python strip() 메서드 완전 정복: 종합 가이드와 실전 예제
  3. Python str.count() 마스터하기: 문자 및 부분문자열 개수 세기 예제
  4. Python format() 문자열 마스터하기: 명확한 예제로 완전 정복
  5. Python len() 함수: 객체 길이 측정 실전 가이드
  6. 파이썬 람다 함수 마스터하기: 실용 예제 & 모범 사례
  7. 파이썬 round() 함수 완전 정복: 실용 예제로 이해하기
  8. 파이썬 map() 함수 마스터하기: 문법, 예제, 모범 사례
  9. 파이썬 timeit()으로 실행 시간 측정하기: 실용 예제
  10. 파이썬 type()과 isinstance() 이해하기: 실전 예제