Validate Character Length
In this step, you will combine the isdigit()
method with length validation to ensure that an input string meets specific criteria. This is a common requirement in many applications, such as validating user input for phone numbers or zip codes.
Let's modify the digit_check.py
file in your ~/project
directory to validate that an input string contains only digits and has a specific length.
Open the digit_check.py
file in the VS Code editor and add the following code:
## ~/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.")
In this code:
- We define a variable
input_string
and assign it the value "12345"
.
- We define a variable
expected_length
and assign it the value 5
.
- We use the
len()
function to get the length of the input string.
- We use the
isdigit()
method to check if the string contains only digits.
- We combine these checks using the
and
operator to ensure that both conditions are met.
- We print a message indicating whether the string is valid or invalid.
To run the script, open your terminal and navigate to the ~/project
directory:
cd ~/project
Then, execute the Python script using the python
command:
python digit_check.py
You should see the following output:
The string '12345' is valid.
Now, let's modify the input_string
to "1234a"
and run the script again:
## ~/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
You should see the following output:
The string '1234a' is invalid.
Finally, let's modify the input_string
to "123456"
and run the script again:
## ~/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
You should see the following output:
The string '123456' is invalid.
This demonstrates how you can combine the isdigit()
method and length validation to create more robust input validation logic.