In this Python string example, we will look into a string based function startswith(). This function takes a parameter and returns true if the given string starts with the supplied parameter.

Syntax

str.startswith(prefix_text,[start],[end])
  • prefix_text can be a string or a tuple. If it is supplied with a tuple, then startswith() function returns true if the given string starts with any value in the tuple.
  • [start] – Optional start position. This will instruct the function to start the comparison from the given position.
  • [end] – Optional end position. End the comparison at the given position.
  • startswith() function is case sensitive.
  • It returns false if no match is found.

Python String startswith – Example

mystr="Example String To Test String functions."
#Returns true as the string starts with given word.
print(mystr.startswith("Example"))
#Returns false as the first letter is not uppercase.
print(mystr.startswith("example"))
#Returns true as the comparison starts from the 8th position and it starts with word "String".
print(mystr.startswith("String",8))
#Use of tuple -  Returns true as one of the values matches the start of the string.
print(mystr.startswith(('functions','Example')))

Output

True
False
True
True
Python String Startswith
Tagged on: