본문 바로가기
카테고리 없음

파이썬 내장함수 count() 예제 코드

by python pro 2023. 2. 14.
반응형

Python의 count() 함수는 문자열에서 특정 문자열이 몇 번 나오는지 카운트하는 기능을 합니다. 이 함수는 문자열에 대한 메소드이며, 특정 문자열의 등장 횟수를 반환합니다.

 

다음은 count() 함수의 기본 형식입니다:

string.count(substring, start, end)
  • substring: 카운트하려는 문자열
  • start: 카운트를 시작할 위치 (선택 인수)
  • end: 카운트를 끝낼 위치 (선택 인수)
# count() 함수 사용
text = "Python is an interpreted, high-level, general-purpose programming language."
count = text.count("Python")
print("Python이 등장하는 횟수:", count)

# 출력: Python이 등장하는 횟수: 1

 

 

text = "Python is an interpreted, high-level, general-purpose programming language."
count = text.count("python")
print("Python이 등장하는 횟수:", count)

# 출력: Python이 등장하는 횟수: 0

위의 잘못된 코드 예시에서는 text 문자열에서 "Python"이라는 문자열이 아닌 "python"이라는 문자열을 카운트하려 했습니다. 대소문자를 구분해서 count 하기 때문에 0이 나오는 것입니다.

 

 

반응형

댓글