Skip to main content

How to check if a string starts with a specific prefix in Python

How to check if a string starts with a specific prefix in Python.

Here's a step-by-step tutorial on how to check if a string starts with a specific prefix in Python:

Step 1: Declare the string and the prefix Start by declaring the string on which you want to perform the check and the specific prefix you want to check for. For example:

string = "Hello, world!"
prefix = "Hello"

Step 2: Use the startswith() method Python provides a built-in method called startswith() that you can use to check if a string starts with a specific prefix. This method returns True if the string starts with the specified prefix, and False otherwise.

result = string.startswith(prefix)

Step 3: Print the result To see the result of the check, you can print the value of the result variable.

print(result)

Step 4: Putting it all together Here's the complete code snippet that performs the check and prints the result:

string = "Hello, world!"
prefix = "Hello"

result = string.startswith(prefix)
print(result)

Output:

True

Additional Examples:

  1. Checking a string with a prefix that matches:
string = "Python programming"
prefix = "Python"

result = string.startswith(prefix)
print(result)

Output:

True
  1. Checking a string with a prefix that does not match:
string = "Python programming"
prefix = "Java"

result = string.startswith(prefix)
print(result)

Output:

False

That's it! You now know how to check if a string starts with a specific prefix in Python.