Python String startswith() Method
The startswith()
method returns True if a string starts with the specified prefix.
If not, it returns False. A tuple of prefixes can also be specified to look for.
Synatx:
str.startswith(prefix, start, end)
Parameters:
- prefix : Required. String or tuple of strings to look for.
- start : Optional. The index position of the character in the string from which the search should start.
- end : Optional. The index position of the character in the string at which the search should end.
Return Value:
Returns True if a string prefixed with the specified prefix; otherwise, returns False.
mystr = 'Hello World'
print(mystr.startswith('')) # always returns True
print(mystr.startswith('H'))
print(mystr.startswith('He'))
print(mystr.startswith('Hello'))
print(mystr.startswith('Hello W'))
print(mystr.startswith('Hello World'))
True
True
True
True
True
True
The startswith()
search is case-sensitive, as shown below.
mystr = 'Hello World'
print(mystr.startswith('h'))
print(mystr.startswith('he'))
print(mystr.startswith('hello'))
False
False
False
The start
and end
parameters limit the checking of a prefix in a string as indexes.
An index starts from 0, i.e. first char's index is 0, second char's index is 1, and so on.
If the end
parameter is not specified, then it search till the end of a string.
mystr = 'Hello World'
print(mystr.startswith('e', 1)) # starts from 'H->ello World'
print(mystr.startswith('ll', 2)) # starts from 'He->llo World'
print(mystr.startswith('World', 6)) # starts from 'Hello ->World'
print(mystr.startswith('Wor', 6, 9)) # starts from 'Hello ->World'
True
True
True
True
Now, consider the following example.
mystr = '''
Python
is a programming language.'''
print(mystr.startswith(''))
print(mystr.startswith('\n'))
print(mystr.startswith('Python'))
True
True
False
Passing a Tuple
The following example contains a tuple of prefixes to look for.
langs = 'Python is a programming language'
print(langs.startswith(('Python','C#','Java')) # return True
greet = 'Hi'
print(greet.startswith(('Hello','Hey',"What's up?")) # returns False
True
False