top of page
Vinay

Checking if a String Starts or Ends with a Specific Substring in Python:


Follop

Introduction:

When working with strings in Python, it is often necessary to check if a string starts or ends with a specific substring. Python provides two convenient methods, startswith() and endswith(), that make it easy to perform such checks efficiently and effectively. In this article, we will explore these two methods in detail and demonstrate how to use them with practical examples.


Understanding startswith() and endswith()

Python's startswith() and endswith() methods are built-in string methods that return True or False depending on whether a string starts or ends with a given substring, respectively. These methods are commonly used in string manipulation, input validation, and conditional branching within programs.


The syntax for startswith() is:

string.startswith(substring)

And the syntax for endswith() is:

string.endswith(substring)

Both methods take a single argument, substring, which represents the specific substring that you want to check for at the beginning or end of the string.


Using startswith() and endswith() with Examples

Example 1: Checking if a String Starts with a Specific Substring

Let's say we have a string variable named text containing the sentence: "Python programming is awesome!"

To check if text starts with the substring "Python," we can use the startswith() method as follows:



text = "Python programming is awesome!"
if text.startswith("Python"):
    print("The string starts with 'Python'")
else:
    print("The string does not start with 'Python'")

Output:

The string starts with 'Python'


Example 2: Checking if a String Ends with a Specific Substring

In this example, suppose we have a string named filename storing the name of a file: "my_document.txt"

To determine if filename ends with the extension ".txt," we can utilize the endswith() method as shown below:


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

Output:

The file is a text file

Conclusion

The startswith() and endswith() methods are powerful tools in Python for checking if a string starts or ends with a specific substring. They provide a simple and efficient way to perform such checks, allowing you to control the flow of your program based on these conditions. By utilizing these methods effectively, you can enhance your string manipulation and input validation tasks.


Remember, understanding and utilizing built-in methods like startswith() and endswith() can significantly improve your code's readability, maintainability, and overall efficiency.



Follop


761 views0 comments

Comments


bottom of page