python에서 날짜와 같은 숫자를 변환하고 싶을 때, 체크하는 함수를 쓰고 싶을 때 사용할 수 있는 코드이다.
int()는 형변환하다가 에러나면 exception 처리 코드에서 확인할 수 있고, 길이는 len으로 확인할 수 있다.
#!/bin/python
def isInt(value):
try:
int(value)
return True
except ValueError:
return False
def is4Digit(value):
try:
if len(value) == 4:
return True
return False
except ValueError:
return False
print isInt("m")
print isInt("2016")
print isInt("1111111111")
print isInt("123@")
print is4Digit("1234444")
print is4Digit("1234")
결과
False
True
True
False
False
True
실제 코드는 아래처럼 써봤다.
if birth_year is not None and isInt(birth_year) and is4Digit(birth_year) :
'python' 카테고리의 다른 글
DEPRECATION: Python 2.6 is no longer supported by the Python core team (0) | 2016.03.17 |
---|---|
[python] continue와 pass 차이 (0) | 2016.02.29 |
python 2.6 에서 python 2.7.9 업그레이드 하기 (pip 설치도 같이 하기) (0) | 2016.01.29 |
python-gssapi 설치 (0) | 2016.01.25 |
pip 간단 설명서 (0) | 2016.01.25 |