Compare with Desired Length
In this step, you will learn how to compare the length of a string with a desired length. This is a common task in programming, especially when validating user input or processing data that must conform to specific length requirements.
Let's create a scenario where we want to ensure that a username entered by a user is between 3 and 10 characters long. Modify your string_length.py
file in the ~/project
directory to include the following:
## filename: string_length.py
username = input("Enter a username: ")
length = len(username)
if length < 3:
print("Username must be at least 3 characters long.")
elif length > 10:
print("Username must be no more than 10 characters long.")
else:
print("Username is valid.")
Save the file and run it:
python ~/project/string_length.py
If you enter a username that is too short:
Enter a username: ab
The output will be:
Username must be at least 3 characters long.
If you enter a username that is too long:
Enter a username: abcdefghijk
The output will be:
Username must be no more than 10 characters long.
If you enter a valid username:
Enter a username: abcdef
The output will be:
Username is valid.
This example demonstrates how you can use the len()
function to check if a string meets specific length criteria.
Now, let's consider a more complex scenario where we want to validate a password. The password must be between 8 and 16 characters long and must contain at least one digit. Modify your string_length.py
file as follows:
## filename: string_length.py
password = input("Enter a password: ")
length = len(password)
has_digit = False
for char in password:
if char.isdigit():
has_digit = True
break
if length < 8:
print("Password must be at least 8 characters long.")
elif length > 16:
print("Password must be no more than 16 characters long.")
elif not has_digit:
print("Password must contain at least one digit.")
else:
print("Password is valid.")
Save the file and run it:
python ~/project/string_length.py
If you enter a password that is too short:
Enter a password: abcdefg
The output will be:
Password must be at least 8 characters long.
If you enter a password that is too long:
Enter a password: abcdefghijklmnopq
The output will be:
Password must be no more than 16 characters long.
If you enter a password that does not contain a digit:
Enter a password: abcdefgh
The output will be:
Password must contain at least one digit.
If you enter a valid password:
Enter a password: abcdefg1
The output will be:
Password is valid.
This example demonstrates how you can combine the len()
function with other techniques, such as looping through the string to check for specific characters, to perform more sophisticated validation.