Skip to content

Python String startswith: Check if String Starts With Substring

Python String startswith Check if String Starts With Substring Cover Image

The Python startswith method is used to check if a string starts with a specific substring. In this tutorial, you’ll learn how to use the Python startswith function to evaluate whether a string starts with one or more substrings. Being able to check if a string starts with another string is a useful way to check user input, such as for phone numbers or names. Alternatively, you can use the startswithmethod to check if a string ends with a substring.

By the end of this tutorial, you’ll have learned:

  • How to use the Python startswith() function to check if a string starts with a substring
  • How to use the Python startswith() function with multiple strings
  • How to use the Python startswith() function without case sensitivity
  • How to use the Python startswith() function with a list of strings

Understanding the Python startswith Function

Before diving into how to use the Python startswith() function, it’s essential to understand the syntax of the function. The code block below breaks down the different required and optional parameters that the function has to offer.

# Understanding the Python startswith() Function
str.startswith(prefix, start, end)

The table below breaks down the parameters of the function as well as any default arguments that the function provides:

ParameterDescriptionDefault ArgumentAccepted Values
prefix=The prefix to check if a given strings starts withN/Astring or tuple of strings
start=The beginning position to check atNoneinteger
end=Stop comparing string at that positionNoneinteger
Understanding the Python startswith() function

Now that you have a strong understanding of the function, let’s start exploring how you can use it.

Using Python startswith to Check if a String Starts with a Substring

The Python startswith() function checks whether or not a string starts with a substring and returns a boolean value. The function will return True if the string starts with the provided substrings and False otherwise. It’s important to note that the function is case-sensitive, so using lower or upper cases will require careful consideration.

Let’s take a look at an example:

# Using Python startswith() to Check if a String Starts with a Substring
text = 'Welcome to datagy.io'

print('text starts with "W": ', text.startswith('W'))
print('text starts with "w": ', text.startswith('w'))

# Returns:
# text starts with "W":  True
# text starts with "w":  False

We can see from the example above that when we check whether or not the string starts with 'W' and 'w'. The first returns True, while the second returns False.

Similarly, we can use the start= parameter to change the starting position of where to check. Because Python strings are 0-based indexed, we can use these index positions. Let’s start checking if the string’s second letter starts with an 'e':

# Modifying the Start Position of the startswith() Function
text = 'Welcome to datagy.io'
print(text.startswith('e', 1))

# Returns: True

Using this is the same as slicing the string to that starting position. In the example above, this could be re-written as text[1:].startswith('e'). However, using the start= parameter is much cleaner to read.

In the following section, you’ll learn how to check if a string starts with multiple different substrings.

Using Python startswith to Check if a String Starts with Multiple Substrings

There may be times when you want to check if a string starts with any of a set of substrings. This means that if you’re looking for, say, a pattern, you can check across different options.

In order to do this, you can simply pass a tuple of strings into the .startswith() method. This will check whether the string starts with any of the options. Let’s see what this looks like with Python:

# Checking if a String Starts With Multiple Different Substrings
text = 'Welcome to datagy.io'
print(text.startswith(('W', 'w')))

# Returns: True

In the code block above, we passed a tuple containing lower-case and upper-case w’s into the method. This allows us to check whether the string starts with either of those letters. In this case, the method returned true, indicating that the string starts with either of those letters.

Using Python startswith to Check if a String Starts with a Substring Case Insensitive

In this section, you’ll learn how to use the Python .startswith() method to check if a string starts with a substring using case insensitivity. By default, the method is case-sensitive and there isn’t a parameter to change this.

Because of this, we have two options for using the .startswith() method with case insensitivity:

  1. Passing in all options of case sensitivity
  2. Transforming the string to lowercase

Let’s take a look at the first option:

# Checking if a String Starts With Substring Using Case Insensitivity
text = 'Welcome to datagy.io'
print(text.startswith(('W', 'w')))

# Returns: True

In the code block above, we checked whether the string starts with a lowercase or uppercase 'w', by passing in a tuple of the two letters. This method works when there are fewer combinations of options, but would be exhaustive otherwise.

Alternatively, we can represent the string in its lowercase equivalent and check for a lowercase substring. Let’s see what this looks like:

# Checking if a String Starts With Substring Using Case Insensitivity
text = 'Welcome to datagy.io'
print(text.lower().startswith(('w')))

# Returns: True

In the code block above, we first use the .lower() method to represent the string in lowercase. Then, we can use the .startswith() method to check if a string starts with a pattern using case insensitivity.

Using Python startswith to Check if a List of Strings Start with a Substring

In this section, you’ll learn how to use the Python .startswith() method to check if items in a list of strings start with a substring. This can be helpful when you want to iterate over all the strings in a list to see whether they start with a substring. In order to do this, we can use a list comprehension, which allows us to simplify the iteration.

# Checking a List of Strings to Check if Strings Start With Substring
texts = ['welcome', 'to', 'datagy']
starts = [True if text.startswith('w') else False for text in texts]

print(starts)

# Returns: [True, False, False]

In the code block above, we use a list comprehension that iterates over a list of strings. The comprehension returns True if the string starts with a given substring and returns False otherwise.

If you want to check if any of the strings start with a substring, you can pass this list comprehension into the Python any() function. The function returns True if any of the items in the passed in array are true. Let’s see what this looks like:

# Checking a List of Strings to Check if Strings Start With Substring
texts = ['welcome', 'to', 'datagy']
starts = any([True if text.startswith('w') else False for text in texts])

print(starts)

# Returns: True

Using Python startswith to Check if a String Does Not Start with a Substring

In this final section, you’ll learn how to use the Python startswith() method to check whether or not a string doesn’t start with a given string. This can be particularly helpful when you want to ensure that a string doesn’t start with something. For example, you may want to check if a phone number doesn’t belong to a particular area code.

# Check if a String Doesn't Start with a Substring
text = 'Welcome to datagy.io'
print(not text.startswith(('W')))

# Returns: False

In the code block above, we preface calling the .startswith() method with the not operator. This returns the inverse boolean of what the method returns. In the example above, we check whether the string starts with 'W' (which it does). However, because we apply not, the program returns False.

Conclusion

In this post, you learned how to use the Python .startswith() method to check whether or not a string starts with a particular substring. You first learned how the method works by exploring its parameters and default arguments. Then, you learned how to use the method to check whether a string starts with a particular substring as well as multiple different substrings.

Then, you learned how to check for strings starting with a substring with case insensitivity. Finally, you checked whether strings in a list start with a given substring and whether or not a string doesn’t start with a substring.

Additional Resources

To learn more about related topics, check out the tutorials below:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

Leave a Reply

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