endswith() 메서드 사용하기
이 단계에서는 endswith() 메서드를 더 자세히 살펴보고 다양한 응용 분야를 탐구합니다. endswith() 메서드는 문자열이 특정 접미사로 끝나는지 확인하는 강력한 도구입니다. 문자열이 지정된 접미사로 끝나면 True를 반환하고, 그렇지 않으면 False를 반환합니다.
이전 단계에서 사용한 suffix_example.py 파일을 계속 사용해 보겠습니다. 스크립트를 수정하여 더 상호 작용하도록 만들 것입니다.
-
VS Code 편집기에서 suffix_example.py 파일을 엽니다.
-
사용자에게 파일 이름을 묻고 .txt로 끝나는지 확인하도록 코드를 수정합니다.
filename = input("Enter a filename: ")
if filename.endswith(".txt"):
print("The file is a text document.")
else:
print("The file is not a text document.")
이 코드는 input() 함수를 사용하여 사용자로부터 파일 이름을 가져옵니다. 그런 다음 endswith() 메서드를 사용하여 파일 이름이 .txt로 끝나는지 확인합니다.
-
suffix_example.py 파일을 저장합니다.
-
스크립트를 실행합니다.
python suffix_example.py
스크립트는 파일 이름을 입력하라는 메시지를 표시합니다.
Enter a filename:
-
my_document.txt를 입력하고 Enter 키를 누릅니다. 다음 출력을 볼 수 있습니다.
The file is a text document.
-
스크립트를 다시 실행하고 my_document.pdf를 입력합니다. 다음 출력을 볼 수 있습니다.
The file is not a text document.
이제 endswith() 메서드의 대소문자 구분 (case sensitivity) 을 살펴보겠습니다.
-
VS Code 편집기에서 suffix_example.py 파일을 엽니다.
-
.TXT (대문자) 를 확인하도록 코드를 수정합니다.
filename = input("Enter a filename: ")
if filename.endswith(".TXT"):
print("The file is a text document (uppercase).")
else:
print("The file is not a text document (uppercase).")
-
suffix_example.py 파일을 저장합니다.
-
스크립트를 실행합니다.
python suffix_example.py
-
my_document.txt를 입력하고 Enter 키를 누릅니다. 다음 출력을 볼 수 있습니다.
The file is not a text document (uppercase).
이것은 endswith() 메서드가 대소문자를 구분함을 보여줍니다. 대소문자를 구분하지 않는 검사를 수행하려면 endswith()를 사용하기 전에 lower() 메서드를 사용하여 문자열을 소문자로 변환할 수 있습니다.
filename = input("Enter a filename: ")
if filename.lower().endswith(".txt"):
print("The file is a text document (case-insensitive).")
else:
print("The file is not a text document (case-insensitive).")
이 수정된 코드는 접미사의 대소문자에 관계없이 my_document.txt를 텍스트 문서로 올바르게 식별합니다.