如何在 Python 中检查字符串是否具有特定长度

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在这个实验中,你将学习如何在 Python 中检查字符串是否具有特定长度。这涉及到理解字符串长度,并使用 len() 函数来确定字符串中的字符数量,包括空格和特殊字符。

你将首先创建一个 Python 脚本,以查找预定义字符串的长度,然后修改该脚本以接受用户输入并计算输入字符串的长度。最后,你将学习如何将字符串的长度与所需长度进行比较,以检查它是否符合特定要求。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) 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{{"如何在 Python 中检查字符串是否具有特定长度"}} python/conditional_statements -.-> lab-559572{{"如何在 Python 中检查字符串是否具有特定长度"}} python/for_loops -.-> lab-559572{{"如何在 Python 中检查字符串是否具有特定长度"}} python/build_in_functions -.-> lab-559572{{"如何在 Python 中检查字符串是否具有特定长度"}} end

理解字符串长度

在这一步中,你将学习如何在 Python 中确定字符串的长度。理解字符串长度是编程中的一个基本概念,因为它能让你有效地处理和操作文本数据。

在 Python 中,len() 函数用于查找字符串的长度。字符串的长度是指它包含的字符数量,包括空格和特殊字符。

让我们从一个简单的例子开始。使用 VS Code 编辑器在你的 ~/project 目录下创建一个名为 string_length.py 的新文件。

## 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)

保存文件,然后在终端中使用以下命令运行脚本:

python ~/project/string_length.py

你应该会看到以下输出:

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

如你所见,len() 函数返回每个字符串中的字符数量。空字符串的长度为 0。

现在,让我们尝试一个带有用户输入的例子。将 string_length.py 文件修改如下:

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

保存文件并再次运行:

python ~/project/string_length.py

脚本会提示你输入一个字符串。输入任意字符串并按回车键。例如:

Enter a string: Python is fun!

输出将是:

The length of the string you entered is: 14

这展示了你如何使用 len() 函数来确定用户提供的字符串的长度。

使用 len() 函数

在这一步中,你将通过将 len() 函数应用于不同场景来加深对它的理解。你将学习如何将其用于各种数据类型,并探索它在处理特殊字符和空白字符时的表现。

首先,让我们来研究 len() 如何处理包含特殊字符和空白字符的字符串。修改 ~/project 目录下的 string_length.py 文件,添加以下内容:

## 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)

保存文件并运行:

python ~/project/string_length.py

你应该会看到以下输出:

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

注意,string1 中的前导和尾随空格被计入长度。此外,string2 中的 Unicode 字符每个都被计为一个字符。string3 中的换行符 \n 也被计为一个字符。

现在,让我们探索如何将 len() 与其他字符串方法结合使用。例如,你可以用它来检查去除空白字符后字符串是否为空。将 string_length.py 文件修改如下:

## 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)

保存文件并运行:

python ~/project/string_length.py

输入一个带有前导和尾随空格的字符串:

Enter a string:   Hello

输出将是:

The length of the string after removing whitespace is: 5

如果你只输入空格,输出将是:

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

这个例子展示了你如何将 len() 函数与 strip() 方法结合使用,以执行更复杂的字符串操作。strip() 方法会去除字符串中的所有前导和尾随空白字符。

与期望长度进行比较

在这一步中,你将学习如何将字符串的长度与期望的长度进行比较。这在编程中是一项常见的任务,特别是在验证用户输入或处理必须符合特定长度要求的数据时。

让我们创建一个场景,确保用户输入的用户名长度在 3 到 10 个字符之间。修改 ~/project 目录下的 string_length.py 文件,添加以下内容:

## 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.")

保存文件并运行:

python ~/project/string_length.py

如果你输入的用户名太短:

Enter a username: ab

输出将是:

Username must be at least 3 characters long.

如果你输入的用户名太长:

Enter a username: abcdefghijk

输出将是:

Username must be no more than 10 characters long.

如果你输入的用户名有效:

Enter a username: abcdef

输出将是:

Username is valid.

这个例子展示了你如何使用 len() 函数来检查字符串是否满足特定的长度标准。

现在,让我们考虑一个更复杂的场景,即验证密码。密码长度必须在 8 到 16 个字符之间,并且必须至少包含一个数字。将 string_length.py 文件修改如下:

## 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.")

保存文件并运行:

python ~/project/string_length.py

如果你输入的密码太短:

Enter a password: abcdefg

输出将是:

Password must be at least 8 characters long.

如果你输入的密码太长:

Enter a password: abcdefghijklmnopq

输出将是:

Password must be no more than 16 characters long.

如果你输入的密码不包含数字:

Enter a password: abcdefgh

输出将是:

Password must contain at least one digit.

如果你输入的密码有效:

Enter a password: abcdefg1

输出将是:

Password is valid.

这个例子展示了你如何将 len() 函数与其他技术(如遍历字符串以检查特定字符)结合使用,以执行更复杂的验证。

总结

在这个实验中,你学习了如何使用 Python 的 len() 函数来确定字符串的长度。本实验展示了如何计算预定义字符串(包括空字符串)的长度,以及如何获取用户输入的字符串并计算其长度。

提供的示例表明,len() 函数会返回字符串中的字符数量,包括空格和特殊字符,并且空字符串的长度为 0。你还练习了从终端运行 Python 脚本并观察输出。