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
Parameter | Required / Optional | Description |
---|---|---|
value | Required | A string value. Specifies the value to search for, in the string. |
start | Optional | An integer. Specifies the position in the string from which the search happens. |
end | Optional | An integer. Specifies the position in the string until which the search happens. |
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)
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)
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)
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.