Use endswith() Method
In this step, you will delve deeper into the endswith() method and explore its various applications. The endswith() method is a powerful tool for checking if a string ends with a specific suffix. It returns True if the string ends with the specified suffix, and False otherwise.
Let's continue with the suffix_example.py file from the previous step. We will modify the script to make it more interactive.
-
Open the suffix_example.py file in the VS Code editor.
-
Modify the code to prompt the user for a filename and then check if it ends with .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.")
This code uses the input() function to get a filename from the user. Then, it uses the endswith() method to check if the filename ends with .txt.
-
Save the suffix_example.py file.
-
Run the script:
python suffix_example.py
The script will prompt you to enter a filename.
Enter a filename:
-
Enter my_document.txt and press Enter. You should see the following output:
The file is a text document.
-
Run the script again and enter my_document.pdf. You should see the following output:
The file is not a text document.
Now, let's explore the case sensitivity of the endswith() method.
-
Open the suffix_example.py file in the VS Code editor.
-
Modify the code to check for .TXT (uppercase):
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).")
-
Save the suffix_example.py file.
-
Run the script:
python suffix_example.py
-
Enter my_document.txt and press Enter. You should see the following output:
The file is not a text document (uppercase).
This demonstrates that the endswith() method is case-sensitive. To perform a case-insensitive check, you can convert the string to lowercase using the lower() method before using endswith().
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).")
This modified code will correctly identify my_document.txt as a text document, regardless of the case of the suffix.