Skip to main content

How to check if a string starts with a certain substring in Python

How to check if a string starts with a certain substring in Python.

Here is a step-by-step tutorial on how to check if a string starts with a certain substring in Python:

Step 1: Start by defining the string that you want to check. Let's call it my_string.

Step 2: Define the substring that you want to check if my_string starts with. Let's call it substring.

Step 3: Use the startswith() function to check if my_string starts with substring. This function returns True if the string starts with the specified substring, and False otherwise.

Here's an example code snippet that demonstrates the above steps:

my_string = "Hello, World!"
substring = "Hello"

if my_string.startswith(substring):
print(f"{my_string} starts with {substring}")
else:
print(f"{my_string} does not start with {substring}")

Output:

Hello, World! starts with Hello

In this example, since the my_string starts with the substring, the condition my_string.startswith(substring) evaluates to True, and the corresponding message is printed.

You can also perform case-insensitive checks by converting both the string and the substring to lowercase or uppercase before using the startswith() function. Here's an example:

my_string = "Hello, World!"
substring = "hello"

if my_string.lower().startswith(substring.lower()):
print(f"{my_string} starts with {substring} (case-insensitive)")
else:
print(f"{my_string} does not start with {substring} (case-insensitive)")

Output:

Hello, World! starts with hello (case-insensitive)

In this case, the lower() function is used to convert both the my_string and the substring to lowercase. This ensures that the check is case-insensitive.

That's it! You've learned how to check if a string starts with a certain substring in Python.