문자열에서 특정 문자나 문자열을 찾고, 찾은 문자열의 Index를 리턴하는 함수를 소개합니다.
1. find() : 문자열에서 문자열 찾기
find(str)는 문자열에서 인자로 전달된 문자열을 찾고 그 문자열의 index를 리턴합니다. 대소문자를 구분하며, 찾는 문자열이 없을 때는 -1을 리턴합니다.
str = "Hello, World, Python"
print(str.find('o'))
print(str.find('World'))
print(str.find('world'))Output:
4
7
-12. rfind() : 반대 방향으로 문자열 찾기
rfind()는 find()와 사용 방법이 정확히 동일하지만, 문자열을 찾는 방향이 문자열의 끝에서 앞쪽이라는 것만 다릅니다. 즉, rfind()는 find()의 반대방향으로 문자열을 찾습니다.
아래 예제들은 문자열 끝에서 문자열 앞쪽 방향으로 탐색을 하고, 찾은 문자열의 Index를 리턴합니다.
str = "Hello, World, Python"
print(str.rfind('o'))
print(str.rfind(','))
print(str.rfind('World'))
print(str.rfind('world'))Output:
18
12
7
-13. index() : 문자열에서 문자열 찾기
index()도 find()와 사용 방법이 거의 동일합니다. 문자열을 찾고, 찾은 문자열의 index를 리턴합니다.
str = "Hello, World, Python"
print(str.index('o'))
print(str.index('World'))Output:
4
7차이점은, 찾는 문자열이 없을 때 -1을 리턴하지 않고 아래와 같이 ValueError를 발생시킵니다. 예외에 대한 처리가 필요합니다.
str = "Hello, World, Python"
print(str.index('world'))Output:
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
File "/home/js/IdeaProjects/python-ex/find.py", line 7, in <module>
print(str.index('world'))
ValueError: substring not found4. rindex() : 반대 방향으로 문자열 찾기
rindex()도 index()와 사용 방법이 동일합니다. 대신 문자열의 끝에서 앞쪽으로 탐색을 합니다.
str = "Hello, World, Python"
print(str.rindex('o'))
print(str.rindex('World'))Output:
18
7그리고 find()와 다르게, 찾는 문자열이 없을 때 -1을 리턴하지 않고 ValueError를 발생시킵니다.
print(str.rindex('world'))Output:
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
File "/home/js/IdeaProjects/python-ex/find.py", line 3, in <module>
print(str.rindex('world'))
ValueError: substring not foundLoading script...
Related Posts
- Python - Yaml 파일 파싱하는 방법
- Python - 파일 내용 삭제
- Python - for문에서 리스트 순회 중 요소 값 제거
- Python - 두 리스트에서 공통 요소 값 찾기
- Python - 문자열 앞(뒤)에 0으로 채우기
- Python - 공백으로 문자열 분리
- Python - 중첩 리스트 평탄화(1차원 리스트 변환)
- Python - 16진수 문자열을 Int로 변환
- Python - 두 날짜, 시간 비교
- Python f-string으로 변수 이름, 값 쉽게 출력 (변수명 = )
- Python - nonlocal과 global 사용 방법
- Python 바다코끼리 연산자 := 알아보기
- Python - pip와 requirements.txt로 패키지 관리
- Python - 딕셔너리 보기 좋게 출력 (pprint)
- Python - Requests 사용 방법 (GET/POST/PUT/PATCH/DELETE)
- Python - 온라인 컴파일러 사이트 추천
- Python - os.walk()를 사용하여 디렉토리, 파일 탐색
- Python - 문자열 비교 방법
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - 리스트에서 첫번째, 마지막 요소 가져오는 방법
- Python - 두개의 리스트 하나로 합치기
- Python - 리스트의 첫번째 요소 제거
- Python - 리스트의 마지막 요소 제거
- Python 소수점 버림, 4가지 방법
- Python 코드 안에서 버전 확인 방법
- Python 소수점 반올림, round() 예제
- Python - 리스트 평균 구하기, 3가지 방법
- Python - bytes를 String으로 변환하는 방법
- Python - String을 bytes로 변환하는 방법
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - 람다(Lambda) 함수 사용 방법
- Python - dict 정렬 (Key, Value로 sorting)
- Python - range() 사용 방법 및 예제
- Python - 리스트를 문자열로 변환
- Python - 문자를 숫자로 변환 (String to Integer, Float)