English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python string startswith() usage and example

Python string methods

If the string starts with the specified prefix (string), the startswith() method will return True. If not, it will return False.

The syntax of startswith():

str.startswith(prefix[, start[, end]])

startswith() parameters

The startswith() method can use up to three parameters:

  • prefix -The string or string tuple to be checked

  • start(Optional)-  To check in the stringPrefix ofStart position.

  • end (Optional)-  To check in the stringPrefix ofEnd position.

The return value of startswith()

The startswith() method returns a boolean value.

  • If the string starts with the specified prefix, it returns True.

  • If the string does not start with the specified prefix, it returns False.

Example1The startswith() method does not have start and end parameters

text = "Python is easy to learn."
result = text.startswith('is easy')
# Return False
print(result)
result = text.startswith('Python is')
# Returns True
print(result)
result = text.startswith('Python is easy to learn.')
# Returns True
print(result)

When running the program, the output is:

False
True
True

Example2: startswith() with start and end parameters

text = "Python programming is easy."
# Starting parameter: 7
# 'programming is easy.' string is searched
result = text.startswith('programming is', 7)
print(result)
# start: 7, end: 18
# 'programming' string is searched
result = text.startswith('programming is', 7, 18)
print(result)
result = text.startswith('program', 7, 18)
print(result)

When running the program, the output is:

True
False
True

Passing a tuple to startswith()

In Python, you can pass a tuple of prefixes to the startswith() method.

If the string starts with any item of the tuple, startswith() returns True. If not, it returns False

Example3: startswith() with tuple prefix

text = "programming is easy"
result = text.startswith(('python', 'programming'))
# Output True
print(result)
result = text.startswith(('is', 'easy', 'java'))
# Output False
print(result)
# With start and end parameters
# 'is easy' string is checked
result = text.startswith(('programming', 'easy'), 12, 19)
# Output False
print(result)

When running the program, the output is:

True
False
False

If you need to check if a string ends with a specified suffix, you canin PythonUseendswith() method.

Python string methods