파이썬에서는 '문자열 자료형'을 특정 기준에 따라 판별하는 메서드가 여러 개 있습니다. 이들 메서드는 문자열이 특정 조건을 만족하는지, 아닌지에 따라 불리언(True or False)값을 반환합니다. 한 번 살펴보겠습니다.
1. .isdigit()
- 문자열의 모든 문자가 숫자(0-9)일 때, True를 반환합니다. 그래서 숫자로만 구성된 문자열인지 판별할 때 사용합니다.
# .isdigit()
example = '1234'
print(example.isdigit()) # True 반환
example2 = '1a2b'
print(example2.isdigit()) # False 반환
example3 = '7'
print(example3.isdigit()) # True 반환
2. .isalpha()
- 문자열의 모든 문자가 알파벳일 때, True를 반환합니다.
# .isalpha()
example = 'abcd'
print(example.isalpha()) # True 반환
example2 = 'a1bc'
print(example2.isalpha()) # False 반환
example3 = 'k'
print(example3.isalpha()) # True 반환
3. 기타 문자열 메서드들
- .islower(): 문자열의 모든 알파벳이 소문자일 때, True를 반환합니다.
- .isupper(): 문자열의 모든 알파벳이 대문자일 때, True를 반환합니다.
- .istitle(): 문자열의 모든 단어가 대문자로 시작할 때, True를 반환합니다.
# .islower()
lower_string = "python"
print(lower_string.islower()) # True 반환
# .isupper()
upper_string = "PYTHON"
print(upper_string.isupper()) # True 반환
# .istitle()
title_string = "Python Programming"
print(title_string.istitle()) # True 반환
'Python' 카테고리의 다른 글
[Python] 특정 값이 처음으로 나타나는 인덱스 반환 - index() (0) | 2024.03.09 |
---|---|
[Python] 원하는 기준으로 이차원 배열 정렬 - sort(), sorted() 및 람다함수 (2) | 2024.03.01 |
[Python] in 연산자 (0) | 2024.02.29 |
[Python] Iterable 객체 생성 - 이터레이터 & 제너레이터 (0) | 2024.02.29 |
[Python] Iterable 객체의 각 요소 Boolean 검사 - all(), any() 함수 (0) | 2024.02.28 |