Python

Python Method Walkthrough: startswith()

In this tutorial, we will be exploring the Python method known as ‘startswith()’. This is a built-in string method that checks whether a string starts with the specified prefix(string). If it does, it returns True. Otherwise, it returns False.

Usage of startswith()

The syntax for using the startswith() method is as follows:


        str.startswith(prefix[, start[, end]])
    
  • prefix: Required. The value to check if the string starts with.
  • start: Optional. An index where to start the search.
  • end: Optional. An index where to end the search.

Tutorial: Using startswith()

Let’s look at some examples of how to use this method in Python programming:


# Example 1
text = "Python is fun."
result = text.startswith('Python')
print(result)  # Outputs: True

# Example 2
text = "Python is fun."
result = text.startswith('fun', 10)
print(result)  # Outputs: True

# Example 3
text = "Python is fun."
result = text.startswith('is', 7, 9)
print(result)  # Outputs: False

In example one, we are checking if our string starts with ‘Python’. Since it does, our output is True.
In example two, we are checking if our string starts with ‘fun’ from index 10. Since ‘fun’ starts from index 10, our output is True.
In example three, we are checking if our string starts with ‘is’ between index 7 and 9. Since it doesn’t, our output is False.

Conclusion

The startswith() method is a useful tool in Python for checking the beginning of strings. It provides an easy way to validate data and perform operations based on the result. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *