Python string startswith() method example

In this source code example, we will demonstrate how to use the Python string startswith() method to check if a string begins with another string.

Python string startswith() method

The startswith() method returns True if a string starts with another string. Otherwise, it returns False.

The following shows the syntax of the startswith() method:
str.startswith(prefix, [,start [,end ])
The startswith() method accepts three parameters:
  • prefix is a string or a tuple of strings to search for. The prefix parameter is mandatory.
  • start is the position where the method starts looking for the prefix. The start parameter is optional.
  • end is the position in the string where the method stops searching for the prefix. The end parameter is also optional.

Python string startswith() method examples

The following example shows how to use the string startswith() method to check if a string starts with another string:
s = 'Source Code Example'
result = s.startswith('Source')
print(result)

Output:

True
The following example uses the startswith() method to check if a string starts with one of the strings in a tuple:

s = 'Make it work, make it right, make it fast.'
result = s.startswith(('Make','make'))
print(result)

Output:

True
The following example illustrates how to use the startswith() method to check if the string starts with the word make in lowercase starting from position 14:

s = 'Make it work, make it right, make it fast.'
result = s.startswith('make', 14)
print(result)

Output:

True

Related Python String Examples

  1. Python string literals
  2. Python string length example
  3. Python String join() method example
  4. Python string split() method example
  5. Python String index() method example
  6. Python string find() method example
  7. Python string startswith() method example
  8. Python string endswith() method example
  9. Python String lower() method example
  10. Python String upper() method example
  11. Python string title() method example
  12. Python string capitalize() method example
  13. Python string islower() method example
  14. Python string istitle() method example
  15. Python string isupper() method example
  16. Python string swapcase() method example
  17. Python string strip() method example
  18. Python string replace() method example
  19. Python string isdigit() method example
  20. Python string isdecimal() method example
  21. Python string isnumeric() method example
  22. Python string isalpha() method example
  23. Python string isalnum() method example


Comments