Python String startswith()

Python String.startswith() is used to check if this string starts with a specified value. The startswith() method returns a boolean value of True if the starts with specified value, or False if not.

In this tutorial, we will learn the syntax and examples for startswith() method of String class.

Syntax

The syntax to call startswith() method on string x in Python is

x.startswith(value, start, end)

where

ParameterRequired / OptionalDescription
valueRequiredA string value. Specifies the value to search for, in the string.
startOptionalAn integer. Specifies the position in the string from which the search happens.
endOptionalAn integer. Specifies the position in the string until which the search happens.
ADVERTISEMENT

Examples

In the following program, we take a string 'hello world', and check if this string starts with the value 'hello'.

Example.py

x = 'hello world'
result = x.startswith('hello')
print(result)
Try Online

Output

True

In the following program, we pass a start position to startswith() method to search the value from this position.

Example.py

x = 'Sun rises in the east.'
result = x.startswith('rises', 4)
print(result)
Try Online

Output

True

Since, the value is present at the beginning of the search (from start position 4), startswith() returned True.

In the following program, let us take the string and search string, such that, the search value is not present at the begging of the string.

Example.py

x = 'Sun rises in the east.'
result = x.startswith('moon')
print(result)
Try Online

Output

False

Conclusion

In this Python Tutorial, we learned how to check if a string starts with a specified value, using startswith() method, with examples.