How do I check if a string starts with a specific substring in Python?
Ava W
ava w profile pic

In Python, you can check if a string starts with a specific substring using different approaches. Here's a detailed explanation of a few commonly used methods: Using thestartswith() method: Thestartswith() method is a built-in string method that returnsTrue if a string starts with a specified substring, andFalse otherwise.

1
2
3
4
5
6
7

my_string = "Hello, World!"

if my_string.startswith("Hello"):
    print("String starts with 'Hello'.")
else:
    print("String does not start with 'Hello'.")

In this example,my_string.startswith("Hello") checks if the stringmy_string starts with the substring "Hello". If it does, the corresponding message is printed. Using slicing and comparison: Another approach is to use string slicing to extract the first few characters of the string and compare them to the desired substring.

1
2
3
4
5
6
7

my_string = "Hello, World!"

if my_string[:5] == "Hello":
    print("String starts with 'Hello'.")
else:
    print("String does not start with 'Hello'.")

In this example,my_string[:5] extracts the first five characters frommy_string, and the extracted substring is compared to the desired substring "Hello". If they are equal, the corresponding message is printed. Using regular expressions: If you need more complex matching patterns, you can use regular expressions (re module) to check if a string starts with a specific substring.

1
2
3
4
5
6
7
8
9

import re

my_string = "Hello, World!"

if re.match("^Hello", my_string):
    print("String starts with 'Hello'.")
else:
    print("String does not start with 'Hello'.")

In this example,re.match("^Hello", my_string) uses the^ symbol to match the start of the string and checks if it is followed by the substring "Hello". If there is a match, the corresponding message is printed. Regular expressions provide a powerful way to handle more advanced matching patterns, but they might be overkill for simple substring checks. Choose the method that best suits your needs based on the specific substring matching requirements in your program.