Python String startswith()

Python String startswith() method is a built-in function that determines whether the given string starts with a specific sequence of characters. Let’s take a look at syntax and examples of the Python string startswith() method.

Note: If you want to determine whether the given string ends with a specific sequence of characters, then you can use Python String endswith()

startswith() Syntax

The syntax of startswith() method is:

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

startswith() Parameter

The startswith() function can take three parameters

  • prefix– string that needs to be checked in the main string
  • start (optional) – Starting position where prefix needs to be checked within the string.
  • end (optional) – Ending position where prefix needs to be checked within the string.

startswith() Return Value

The startswith() function returns true if the string starts with the specified prefix. Otherwise, it returns false.

Note: The startswith() function is case-sensitive

Example 1: startswith() Without start and end Parameters

text = "Welcome to Python Tutorials"

# startswith is case-sensitive, returns false
print(text.startswith('welcome'))

# returns true
print(text.startswith('Welcome'))

# returns true
print(text.startswith('Welcome to'))

Output

False
True
True

Example 2: startswith() With start and end Parameters

text = "Welcome to Python Tutorials"

# returns true
result = text.startswith("Welcome", 0)
print(result)

# returns false
result = text.startswith("to", 1, 15)
print(result)

# returns true
result = text.startswith("to", 8, 10)
print(result)

Output

True
False
True

Passing Tuple to startswith()

It’s possible to pass a tuple as a prefix to the startswith() method in Python. If the string starts with any item of the tuple, startswith() function returns True. Otherwise it returns False

text = "Welcome to Python Tutorials"

# returns true
result = text.startswith(('Welcome', 'Python', 'Tutorials'))
print(result)

# returns true
result = text.startswith(('to', 'Python', 'Tutorials'), 8)
print(result)

# returns true
result = text.startswith(('to', 'Python', 'Tutorials'), 11, 20)
print(result)

Output

True
True
True
Leave a Reply

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

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
List of Python free ebooks

List of Free Python Books

Table of Contents Hide Python SuccinctlyPython Data Science HandbookThink Python 2nd EditionAutomate the Boring Stuff with PythonMaking Games with Python & PygameData Structures and Algorithms in Python Google Python Style GuideA…
View Post