문자열 길이 검증
이 단계에서는 isdigit() 메서드와 길이 유효성 검사를 결합하여 입력 문자열이 특정 기준을 충족하는지 확인합니다. 이는 전화 번호 또는 우편 번호에 대한 사용자 입력을 검증하는 등 많은 애플리케이션에서 일반적인 요구 사항입니다.
~/project 디렉토리의 digit_check.py 파일을 수정하여 입력 문자열이 숫자만 포함하고 특정 길이를 갖는지 확인해 보겠습니다.
VS Code 편집기에서 digit_check.py 파일을 열고 다음 코드를 추가합니다.
## ~/project/digit_check.py
input_string = "12345"
expected_length = 5
## Check if the string contains only digits and has the expected length
if len(input_string) == expected_length and input_string.isdigit():
print(f"The string '{input_string}' is valid.")
else:
print(f"The string '{input_string}' is invalid.")
이 코드에서:
input_string 변수를 정의하고 값 "12345"를 할당합니다.
expected_length 변수를 정의하고 값 5를 할당합니다.
len() 함수를 사용하여 입력 문자열의 길이를 가져옵니다.
isdigit() 메서드를 사용하여 문자열이 숫자만 포함하는지 확인합니다.
and 연산자를 사용하여 이러한 검사를 결합하여 두 조건이 모두 충족되는지 확인합니다.
- 문자열이 유효한지 또는 유효하지 않은지 나타내는 메시지를 출력합니다.
스크립트를 실행하려면 터미널을 열고 ~/project 디렉토리로 이동합니다.
cd ~/project
그런 다음 python 명령을 사용하여 Python 스크립트를 실행합니다.
python digit_check.py
다음 출력을 볼 수 있습니다.
The string '12345' is valid.
이제 input_string을 "1234a"로 수정하고 스크립트를 다시 실행해 보겠습니다.
## ~/project/digit_check.py
input_string = "1234a"
expected_length = 5
## Check if the string contains only digits and has the expected length
if len(input_string) == expected_length and input_string.isdigit():
print(f"The string '{input_string}' is valid.")
else:
print(f"The string '{input_string}' is invalid.")
python digit_check.py
다음 출력을 볼 수 있습니다.
The string '1234a' is invalid.
마지막으로 input_string을 "123456"으로 수정하고 스크립트를 다시 실행해 보겠습니다.
## ~/project/digit_check.py
input_string = "123456"
expected_length = 5
## Check if the string contains only digits and has the expected length
if len(input_string) == expected_length and input_string.isdigit():
print(f"The string '{input_string}' is valid.")
else:
print(f"The string '{input_string}' is invalid.")
python digit_check.py
다음 출력을 볼 수 있습니다.
The string '123456' is invalid.
이것은 isdigit() 메서드와 길이 유효성 검사를 결합하여 보다 강력한 입력 유효성 검사 로직을 만드는 방법을 보여줍니다.