如何在 Python 中检查字符串是否为空白字符

PythonPythonBeginner
立即练习

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

简介

在这个实验中,你将学习如何在 Python 中检查一个字符串是否完全由空白字符组成。实验首先会定义常见的空白字符,如空格、制表符、换行符、回车符、垂直制表符和换页符。然后,你将创建一个 Python 脚本,来展示这些字符及其对文本格式的影响。

本实验将指导你使用 isspace() 方法来判断一个字符串是否仅包含空白字符。最后,它会区分包含空白字符的字符串和空字符串,强调在 Python 编程中理解这些区别的重要性。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FileHandlingGroup(["File Handling"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/strings("Strings") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/FileHandlingGroup -.-> python/file_operations("File Operations") subgraph Lab Skills python/strings -.-> lab-559582{{"如何在 Python 中检查字符串是否为空白字符"}} python/build_in_functions -.-> lab-559582{{"如何在 Python 中检查字符串是否为空白字符"}} python/file_operations -.-> lab-559582{{"如何在 Python 中检查字符串是否为空白字符"}} end

定义空白字符

在这一步中,你将了解 Python 中的空白字符。空白字符是表示空空间的字符。它们在编程中很重要,因为它们会影响代码的解释和显示方式。理解空白字符对于编写简洁易读的 Python 代码至关重要。

常见的空白字符包括:

  • 空格 ( ): 最常见的空白字符,用于分隔单词和语句。
  • 制表符 (\t): 用于缩进,通常代表四个空格。
  • 换行符 (\n): 用于表示一行的结束。
  • 回车符 (\r): 在较旧的系统中用于将光标移到行首。
  • 垂直制表符 (\v): 较少使用,但仍然是一种空白字符。
  • 换页符 (\f): 用于在打印时前进到下一页。

让我们创建一个 Python 脚本来演示这些字符。

  1. 在 LabEx 环境中打开 VS Code 编辑器。

  2. ~/project 目录下创建一个名为 whitespace_demo.py 的新文件。

    touch ~/project/whitespace_demo.py
  3. 在编辑器中打开 whitespace_demo.py 文件,并添加以下内容:

    ## Demonstrating whitespace characters
    
    space_char = " "
    tab_char = "\t"
    newline_char = "\n"
    carriage_return_char = "\r"
    vertical_tab_char = "\v"
    form_feed_char = "\f"
    
    print("This", space_char, "is", space_char, "separated", space_char, "by", space_char, "spaces.")
    print("This\tis\tseparated\tby\ttabs.")
    print("This" + newline_char + "is" + newline_char + "on" + newline_char + "multiple" + newline_char + "lines.")
    print("This" + carriage_return_char + "will overwrite the beginning of the line.")
    print("Vertical" + vertical_tab_char + "Tab")
    print("Form" + form_feed_char + "Feed")

    这个脚本为每个空白字符定义了变量,然后在 print() 语句中使用它们来演示其效果。

  4. 使用 python 命令运行脚本:

    python ~/project/whitespace_demo.py

    你应该会看到类似于以下的输出:

    This   is   separated   by   spaces.
    This    is      separated       by      tabs.
    This
    is
    on
    multiple
    lines.
     will overwrite the beginning of the line.
    Vertical Tab
    Form Feed

    注意每个空白字符是如何影响输出格式的。换行符会创建换行,制表符会创建水平间距。回车符会覆盖行首。垂直制表符和换页符可能根据你的终端设置而不可见。

使用 isspace() 方法

在这一步中,你将学习如何在 Python 中使用 isspace() 方法来检查一个字符串是否仅由空白字符组成。这个方法对于验证用户输入或清理数据非常有用。

isspace() 方法是一个内置的字符串方法,如果字符串中的所有字符都是空白字符(如空格、制表符、换行符等),并且字符串至少包含一个字符,则返回 True;否则返回 False

让我们创建一个 Python 脚本来演示 isspace() 方法。

  1. 在 LabEx 环境中打开 VS Code 编辑器。

  2. ~/project 目录下创建一个名为 isspace_demo.py 的新文件。

    touch ~/project/isspace_demo.py
  3. 在编辑器中打开 isspace_demo.py 文件,并添加以下内容:

    ## Demonstrating the isspace() method
    
    string1 = "   "  ## Contains only spaces
    string2 = "\t\n"  ## Contains tabs and newlines
    string3 = "  abc  "  ## Contains spaces and letters
    string4 = ""  ## Empty string
    string5 = "123" ## Contains numbers
    
    print(f"'{string1}'.isspace(): {string1.isspace()}")
    print(f"'{string2}'.isspace(): {string2.isspace()}")
    print(f"'{string3}'.isspace(): {string3.isspace()}")
    print(f"'{string4}'.isspace(): {string4.isspace()}")
    print(f"'{string5}'.isspace(): {string5.isspace()}")

    这个脚本定义了几个包含不同组合的空白字符和非空白字符的字符串。然后使用 isspace() 方法来检查每个字符串是否仅由空白字符组成。

  4. 使用 python 命令运行脚本:

    python ~/project/isspace_demo.py

    你应该会看到类似于以下的输出:

    '   '.isspace(): True
    '
    '.isspace(): True
    '  abc  '.isspace(): False
    ''.isspace(): False
    '123'.isspace(): False

    如你所见,isspace() 仅对那些仅包含空白字符且不为空的字符串返回 True

区分空字符串

在这一步中,你将学习在 Python 中区分仅包含空白字符的字符串和空字符串。理解这种区别很重要,因为 isspace() 方法对空字符串的处理方式不同。

正如你在上一步中学到的,如果字符串中的所有字符都是空白字符,并且字符串不为空,isspace() 方法将返回 True。对于空字符串(即没有字符的字符串),isspace() 返回 False

让我们修改上一步中的 isspace_demo.py 脚本,以突出这种区别。

  1. ~/project 目录下的 VS Code 编辑器中打开 isspace_demo.py 文件。

  2. 修改脚本,以包含对空字符串更明确的检查:

    ## Demonstrating the isspace() method and empty strings
    
    string1 = "   "  ## Contains only spaces
    string2 = ""  ## Empty string
    
    print(f"'{string1}'.isspace(): {string1.isspace()}")
    print(f"'{string2}'.isspace(): {string2.isspace()}")
    
    if string2:
        print("string2 is not empty")
    else:
        print("string2 is empty")
    
    if string1.isspace():
        print("string1 contains only whitespace")
    else:
        print("string1 does not contain only whitespace")

    这个脚本现在包含一个 if 语句,用于检查 string2 是否为空。它还检查 string1 是否仅包含空白字符。

  3. 使用 python 命令运行脚本:

    python ~/project/isspace_demo.py

    你应该会看到类似于以下的输出:

    '   '.isspace(): True
    ''.isspace(): False
    string2 is empty
    string1 contains only whitespace

    这个输出清楚地表明,isspace() 对空字符串返回 False,并且 if 语句正确地将 string2 识别为空字符串。

总结

在这个实验中,你学习了 Python 中的空白字符,这些字符代表空的空间,并会影响代码的解释和显示。本实验涵盖了常见的空白字符,如空格、制表符、换行符、回车符、垂直制表符和换页符。

你创建了一个名为 whitespace_demo.py 的 Python 脚本,通过为每个空白字符定义变量,并在 print() 语句中使用它们,来展示这些字符对文本格式和输出的影响。