How to Check If a String Has a Specific Length in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string has a specific length in Python. This involves understanding string length and utilizing the len() function to determine the number of characters in a string, including spaces and special characters.

You'll start by creating a Python script to find the length of predefined strings and then modify the script to accept user input and calculate the length of the entered string. Finally, you will learn how to compare the length of a string with a desired length to check if it matches the specific requirement.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/strings("Strings") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/strings -.-> lab-559572{{"How to Check If a String Has a Specific Length in Python"}} python/conditional_statements -.-> lab-559572{{"How to Check If a String Has a Specific Length in Python"}} python/for_loops -.-> lab-559572{{"How to Check If a String Has a Specific Length in Python"}} python/build_in_functions -.-> lab-559572{{"How to Check If a String Has a Specific Length in Python"}} end

Understand String Length

In this step, you will learn how to determine the length of a string in Python. Understanding string length is a fundamental concept in programming, as it allows you to manipulate and process text data effectively.

In Python, the len() function is used to find the length of a string. The length of a string is the number of characters it contains, including spaces and special characters.

Let's start with a simple example. Create a new file named string_length.py in your ~/project directory using the VS Code editor.

## filename: string_length.py
string1 = "Hello, LabEx!"
length1 = len(string1)
print("The length of the string 'Hello, LabEx!' is:", length1)

string2 = "This is a longer string."
length2 = len(string2)
print("The length of the string 'This is a longer string.' is:", length2)

string3 = ""  ## Empty string
length3 = len(string3)
print("The length of the empty string is:", length3)

Save the file and then run the script using the following command in the terminal:

python ~/project/string_length.py

You should see the following output:

The length of the string 'Hello, LabEx!' is: 13
The length of the string 'This is a longer string.' is: 24
The length of the empty string is: 0

As you can see, the len() function returns the number of characters in each string. An empty string has a length of 0.

Now, let's try another example with user input. Modify the string_length.py file as follows:

## filename: string_length.py
user_string = input("Enter a string: ")
length = len(user_string)
print("The length of the string you entered is:", length)

Save the file and run it again:

python ~/project/string_length.py

The script will prompt you to enter a string. Type any string and press Enter. For example:

Enter a string: Python is fun!

The output will be:

The length of the string you entered is: 14

This demonstrates how you can use the len() function to determine the length of a string provided by the user.

Use len() Function

In this step, you will deepen your understanding of the len() function by applying it to different scenarios. You'll learn how to use it with various data types and explore its behavior with special characters and whitespace.

First, let's examine how len() handles strings with special characters and whitespace. Modify your string_length.py file in the ~/project directory to include the following:

## filename: string_length.py
string1 = "  Hello, LabEx!  "  ## String with leading and trailing spaces
length1 = len(string1)
print("The length of the string with spaces is:", length1)

string2 = "ไฝ ๅฅฝ๏ผŒLabEx!"  ## String with Unicode characters
length2 = len(string2)
print("The length of the string with Unicode characters is:", length2)

string3 = "Line1\nLine2"  ## String with a newline character
length3 = len(string3)
print("The length of the string with a newline is:", length3)

Save the file and run it:

python ~/project/string_length.py

You should see the following output:

The length of the string with spaces is: 17
The length of the string with Unicode characters is: 9
The length of the string with a newline is: 11

Notice that the leading and trailing spaces in string1 are included in the length. Also, the Unicode characters in string2 are each counted as one character. The newline character \n in string3 is also counted as one character.

Now, let's explore how to use len() in conjunction with other string methods. For example, you can use it to check if a string is empty after removing whitespace. Modify your string_length.py file as follows:

## filename: string_length.py
user_string = input("Enter a string: ")
stripped_string = user_string.strip()  ## Remove leading/trailing whitespace
length = len(stripped_string)

if length == 0:
    print("The string is empty after removing whitespace.")
else:
    print("The length of the string after removing whitespace is:", length)

Save the file and run it:

python ~/project/string_length.py

Enter a string with leading and trailing spaces:

Enter a string:   Hello

The output will be:

The length of the string after removing whitespace is: 5

If you enter only spaces, the output will be:

Enter a string:
The string is empty after removing whitespace.

This example demonstrates how you can combine the len() function with the strip() method to perform more complex string operations. The strip() method removes any leading and trailing whitespace from the string.

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.

Summary

In this lab, you learned how to determine the length of a string in Python using the len() function. The lab demonstrated how to calculate the length of predefined strings, including empty strings, and how to obtain string input from the user and then calculate its length.

The examples provided showed that the len() function returns the number of characters in a string, including spaces and special characters, and that an empty string has a length of 0. You also practiced running Python scripts from the terminal and observing the output.