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

파이썬 startswith() endswith() 내장함수 정리

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

Python에서 startswith()와 endswith() 함수는 문자열의 시작과 끝이 특정 문자열로 시작하거나 끝나는지 확인하는데 사용됩니다.

 

startswith() 함수

  • 괄호 안에 넣은 문자열이 현재 문자열의 시작하는 부분과 같은지 확인합니다.
  • 일치하면 True를 반환하고, 그렇지 않으면 False를 반환합니다.
text = "Hello World"
print(text.startswith("Hello")) # True
print(text.startswith("Hi")) # False

 

endswith() 함수

  • 괄호 안에 넣은 문자열이 현재 문자열의 끝부분과 같은지 확인합니다.
  • 일치하면 True를 반환하고, 그렇지 않으면 False를 반환합니다.
text = "Hello World"
print(text.endswith("World")) # True
print(text.endswith("world")) # False

 

이런 곳에서 실제로 사용이 될 수 있습니다.

 

파일 이름에서 특정 확장자 파일 검색

import os

dir_path = '/path/to/dir'

for filename in os.listdir(dir_path):
    if filename.endswith('.txt'):
        print(filename)

 

문자열에서 특정 단어 검색

text = "This is a sample text for searching specific word"

if text.startswith("This"):
    print("The word 'This' is found at the start of the text")

if "specific" in text:
    if text.endswith("word"):
        print("The word 'specific' and 'word' are found in the text")

 

메일 주소 검증

email = "example@gmail.com"

if email.endswith(".com"):
    print("Valid email address")
else:
    print("Invalid email address")
반응형

댓글