Python str.count() 마스터하기: 문자 및 부분문자열 개수 세기 예제
Python str.count() 마스터하기: 문자 및 부분문자열 개수 세기 예제
str.count() 메서드는 지정된 부분문자열이 문자열에 몇 번 나타나는지 반환하는 가볍고 내장된 도구. 단일 문자, 다중 문자 패턴, 텍스트 특정 구간 내 개수 세기 등 모두 빠르고 정밀하게 처리.
str.count() 사용 이유
- 대부분 경우 O(n) 시간 복잡도.
- 제로 의존성: 외부 라이브러리 불필요.
- 전처리, 데이터 검증, 텍스트 빠른 분석에 이상적.
문법 개요
string.count(sub[, start[, end]])
매개변수
sub – 세고 싶은 부분문자열 또는 단일 문자.
start (선택) – 검색 시작 인덱스. 기본 0.
end (선택) – 검색 종료 인덱스 (미포함). 기본 문자열 길이.
반환값
선택적 start와 end 인덱스 사이에서 sub의 중복되지 않는 발생 횟수 나타내는 정수 반환. sub 없으면 0 반환.
실전 예제
예제 1: 단일 문자 세기
str1 = "Hello World"
print("Count of 'o':", str1.count('o'))
print("Count of 'o' between indices 0 and 5:", str1.count('o', 0, 5))
출력:
Count of 'o': 2
Count of 'o' between indices 0 and 5: 1
예제 2: 구문 전체에서 문자 세기
str1 = "Welcome to Guru99 Tutorials!"
print("Count of 'u':", str1.count('u'))
print("Count of 'u' between indices 6 and 15:", str1.count('u', 6, 15))
출력:
Count of 'u': 3
Count of 'u' between indices 6 and 15: 2
예제 3: 긴 텍스트에서 부분문자열 세기
str1 = "Welcome to Guru99 - Free Training Tutorials and Videos for IT Courses"
print("Count of 'to':", str1.count('to'))
print("Count of 'to' between indices 6 and 15:", str1.count('to', 6, 15))
출력:
Count of 'to': 2
Count of 'to' between indices 6 and 15: 1
핵심 요약
str.count()는 중복되지 않는 발생 횟수 정수 반환.
- 선택적
start, end 인자로 특정 슬라이스 검색 제한 가능.
- Python 스크립트에서 빠른 텍스트 분석, 데이터 정제, 특징 추출에 완벽.