[프로그래머스 / Python] 문자열 다루기 기본

https://programmers.co.kr/learn/courses/30/lessons/12918

 

코딩테스트 연습 - 문자열 다루기 기본

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

programmers.co.kr

 

isdigit 함수를 이용하면 쉽게 풀 수 있다.

 

내 코드

def solution(s):
    if len(s) in [4,6]:
        if s.isdigit():
            return True
    return False

 

문자열에서 알파벳인지 숫자인지 확인하는 문제가 많이 나오므로 한번 정리해보자.

 

1. 알파벳인지 확인하기 (isalpha) : 문자열 전체가 모두 알파벳으로 구성되어있는지 확인해줌

# Appia Example for isalpha
 
# It is to explain how to check whether the string consist of alphabet or not.
 
Ex1 = 'A'
Ex2 = 'ABC'
Ex3 = "앱피아"
Ex4 = "Hello Appia"
Ex5 = "100Appia"
 
#print the is the result for isalpha()

print(Ex1.isalpha())
print(Ex2.isalpha())
print(Ex3.isalpha())
print(Ex4.isalpha())
print(Ex5.isalpha())

👉result

True
True
True  # 문자열에 한글이 있어도 True
False # 문자열에 공백이 포함되어있으면 False
False

 

2. 숫자인지 확인하기 (isdigit) : 문자열 전체가 모두 숫자로 구성되어 있는지 확인해줌

# Appia Example for isalpha
 
# It is to explain how to check whether the string consist of digit or not.
 
Ex1 = '010-1234-5678'
Ex2 = '123456'
Ex3 = "R4R3"
 
print(Ex1.isdigit())
print(Ex2.isdigit())
print(Ex3.isdigit())

👉result

False
True
False

 

3. 알페벳 또는 숫자인지 확인하기 (isalnum) : 문자열 전체가 알파벳 또는 숫자로만 구성되어있는지 확인해줌

# Appia Example for isalpha

# It is to explain how to check whether the string consist of digit/alphabet or not.
 
Ex1 = '안녕'
Ex2 = 'Hello3'
Ex3 = "1.Where"
Ex4 = "1 Where"
 
print(Ex1.isalnum())
print(Ex2.isalnum())
print(Ex3.isalnum())
print(Ex4.isalnum())

👉result

True
True
False # .은 알파벳, 숫자가 아니므로 False
False # 공백 포함시 False

댓글

Designed by JB FACTORY