如何在 Python 中检查字符串是否以特定后缀结尾

PythonPythonBeginner
立即练习

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

简介

在这个实验中,你将学习如何使用 Python 的 endswith() 方法来检查字符串是否以特定后缀结尾。这项技能对于文件类型识别和数据验证等任务至关重要。

本实验将指导你创建一个 Python 脚本,用于检查 .pdf.txt 后缀。你将学习如何使用 endswith() 方法来判断字符串是否以特定后缀结尾,以及如何修改脚本以检查不同的后缀。后续步骤将探讨如何检查多个后缀。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/strings("Strings") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/strings -.-> lab-559571{{"如何在 Python 中检查字符串是否以特定后缀结尾"}} python/conditional_statements -.-> lab-559571{{"如何在 Python 中检查字符串是否以特定后缀结尾"}} python/data_collections -.-> lab-559571{{"如何在 Python 中检查字符串是否以特定后缀结尾"}} end

了解字符串后缀

在这一步中,你将了解字符串后缀及其在编程中的重要性。字符串后缀是出现在字符串末尾的子字符串。理解后缀对于文件类型识别、数据验证和文本处理等任务至关重要。

让我们从创建一个简单的 Python 脚本来演示字符串后缀开始。

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

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

    ~/project/suffix_example.py
  3. 将以下 Python 代码添加到 suffix_example.py 文件中:

    filename = "document.pdf"
    
    if filename.endswith(".pdf"):
        print("The file is a PDF document.")
    else:
        print("The file is not a PDF document.")

    这段代码检查字符串变量 filename 是否以后缀 .pdf 结尾。这里使用了 endswith() 方法来实现此目的。

  4. 保存 suffix_example.py 文件。

  5. 在终端中使用 python 命令运行脚本:

    python suffix_example.py

    你应该会看到以下输出:

    The file is a PDF document.

现在,让我们修改脚本以检查不同的后缀。

  1. 在 VS Code 编辑器中打开 suffix_example.py 文件。

  2. 修改代码以检查 .txt 后缀:

    filename = "document.txt"
    
    if filename.endswith(".txt"):
        print("The file is a text document.")
    else:
        print("The file is not a text document.")
  3. 保存 suffix_example.py 文件。

  4. 再次运行脚本:

    python suffix_example.py

    你应该会看到以下输出:

    The file is a text document.

这展示了如何使用 endswith() 方法来检查字符串中特定的后缀。这是许多编程任务的基本技术。

使用 endswith() 方法

在这一步中,你将更深入地了解 endswith() 方法,并探索其各种应用。endswith() 方法是一个强大的工具,用于检查字符串是否以特定后缀结尾。如果字符串以指定的后缀结尾,该方法返回 True,否则返回 False

让我们继续使用上一步中的 suffix_example.py 文件。我们将修改脚本,使其更具交互性。

  1. 在 VS Code 编辑器中打开 suffix_example.py 文件。

  2. 修改代码,提示用户输入一个文件名,然后检查该文件名是否以 .txt 结尾:

    filename = input("Enter a filename: ")
    
    if filename.endswith(".txt"):
        print("The file is a text document.")
    else:
        print("The file is not a text document.")

    这段代码使用 input() 函数从用户那里获取一个文件名。然后,使用 endswith() 方法检查该文件名是否以 .txt 结尾。

  3. 保存 suffix_example.py 文件。

  4. 运行脚本:

    python suffix_example.py

    脚本会提示你输入一个文件名。

    Enter a filename:
  5. 输入 my_document.txt 并按回车键。你应该会看到以下输出:

    The file is a text document.
  6. 再次运行脚本,输入 my_document.pdf。你应该会看到以下输出:

    The file is not a text document.

现在,让我们探索 endswith() 方法的大小写敏感性。

  1. 在 VS Code 编辑器中打开 suffix_example.py 文件。

  2. 修改代码,检查 .TXT(大写)后缀:

    filename = input("Enter a filename: ")
    
    if filename.endswith(".TXT"):
        print("The file is a text document (uppercase).")
    else:
        print("The file is not a text document (uppercase).")
  3. 保存 suffix_example.py 文件。

  4. 运行脚本:

    python suffix_example.py
  5. 输入 my_document.txt 并按回车键。你应该会看到以下输出:

    The file is not a text document (uppercase).

这表明 endswith() 方法是区分大小写的。要进行不区分大小写的检查,你可以在使用 endswith() 之前,使用 lower() 方法将字符串转换为小写。

filename = input("Enter a filename: ")

if filename.lower().endswith(".txt"):
    print("The file is a text document (case-insensitive).")
else:
    print("The file is not a text document (case-insensitive).")

这段修改后的代码将正确地将 my_document.txt 识别为文本文件,而不考虑后缀的大小写。

检查多个后缀

在这一步中,你将学习如何检查一个字符串是否以多个后缀中的任意一个结尾。当你想根据可能的扩展名列表来识别文件时,这非常有用。

让我们修改 suffix_example.py 文件以检查多个后缀。

  1. 在 VS Code 编辑器中打开 suffix_example.py 文件。

  2. 修改代码,检查文件名是否以 .txt.pdf 结尾:

    filename = input("Enter a filename: ")
    suffixes = (".txt", ".pdf")
    
    if filename.endswith(suffixes):
        print("The file is either a text document or a PDF document.")
    else:
        print("The file is neither a text document nor a PDF document.")

    在这段代码中,我们定义了一个名为 suffixes 的元组,其中包含我们要检查的后缀。endswith() 方法可以接受一个后缀元组作为参数。

  3. 保存 suffix_example.py 文件。

  4. 运行脚本:

    python suffix_example.py

    脚本会提示你输入一个文件名。

    Enter a filename:
  5. 输入 my_document.txt 并按回车键。你应该会看到以下输出:

    The file is either a text document or a PDF document.
  6. 再次运行脚本,输入 my_document.pdf。你应该会看到以下输出:

    The file is either a text document or a PDF document.
  7. 再次运行脚本,输入 my_document.docx。你应该会看到以下输出:

    The file is neither a text document nor a PDF document.

现在,让我们在元组中添加另一个后缀。

  1. 在 VS Code 编辑器中打开 suffix_example.py 文件。

  2. 修改代码,检查文件名是否以 .txt.pdf.docx 结尾:

    filename = input("Enter a filename: ")
    suffixes = (".txt", ".pdf", ".docx")
    
    if filename.endswith(suffixes):
        print("The file is either a text document, a PDF document, or a Word document.")
    else:
        print("The file is neither a text document, a PDF document, nor a Word document.")
  3. 保存 suffix_example.py 文件。

  4. 运行脚本:

    python suffix_example.py
  5. 输入 my_document.docx 并按回车键。你应该会看到以下输出:

    The file is either a text document, a PDF document, or a Word document.

这展示了如何使用 endswith() 方法和一个后缀元组来检查多种可能的文件类型。

总结

在这个实验中,你了解了字符串后缀及其在编程中的重要性,特别是在文件类型识别等任务中。你使用 endswith() 方法创建了一个 Python 脚本,用于检查文件名字符串是否以特定后缀(如 ".pdf" 和 ".txt")结尾。

本实验展示了如何修改脚本以检查不同的后缀,并验证了每种情况下的输出,说明了使用 endswith() 进行字符串后缀验证的基本技巧。