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

Python str.count() 마스터하기: 문자 및 부분문자열 개수 세기 예제

Python str.count() 마스터하기: 문자 및 부분문자열 개수 세기 예제

str.count() 메서드는 지정된 부분문자열이 문자열에 몇 번 나타나는지 반환하는 가볍고 내장된 도구. 단일 문자, 다중 문자 패턴, 텍스트 특정 구간 내 개수 세기 등 모두 빠르고 정밀하게 처리.

str.count() 사용 이유

문법 개요

string.count(sub[, start[, 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

핵심 요약

python

  1. Java String.indexOf() 마스터: 부분문자열 위치 찾기 & 실전 예제
  2. Python strip() 메서드 완전 정복: 종합 가이드와 실전 예제
  3. Python format() 문자열 마스터하기: 명확한 예제로 완전 정복
  4. Python String.find() 메서드 마스터하기: 문법, 예제, 대안 비교
  5. 파이썬 람다 함수 마스터하기: 실용 예제 & 모범 사례
  6. 파이썬 round() 함수 완전 정복: 실용 예제로 이해하기
  7. 파이썬 map() 함수 마스터하기: 문법, 예제, 모범 사례
  8. 파이썬 timeit()으로 실행 시간 측정하기: 실용 예제
  9. 파이썬 collections.Counter: 효율적 카운팅, 업데이트, 산술 연산
  10. 파이썬 type()과 isinstance() 이해하기: 실전 예제