본문 바로가기

Python

[Python] 문자열 다루기 기본, .isdigit()

문제 설명

문자열 s의 길이가 4 혹은 6이고, 숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요. 예를 들어 s가 "a234"이면 False를 리턴하고 "1234"라면 True를 리턴하면 됩니다.

 

.isdigit()

str.isdigit()
    • Return True if all characters in the string are digits and there is at least one character, False otherwise.
      • Return True: digits(지수, 밑수 등도 포함)이면 True 반환
      • Return Flase: 1글자라도 문자가 들어가면 False 반환
    • Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.
    • Exponents, like ², are also considered to be a digit.
    • 참고자료: Python 공식 문서, w3schools

 

code

def solution(s):
    if len(s) == 4 or len(s) == 6:
        if s.isdigit():
            return True
    return False
  • 첫번째 if문: 문자열 s의 길이 비교하고 True면 다음 if문 실행
  • 두번째 if문: 문자열 s가 digit이면 return True
  • 첫번째, 두번째 if문을 모두 통과하지 못하면 return False

 

반응형