English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
If the string starts with the specified prefix (string), the startswith() method will return True. If not, it will return False.
The syntax of startswith():
str.startswith(prefix[, start[, end]])
The startswith() method can use up to three parameters:
prefix -The string or string tuple to be checked
start(Optional)- To check in the stringPrefix ofStart position.
end (Optional)- To check in the stringPrefix ofEnd position.
The startswith() method returns a boolean value.
If the string starts with the specified prefix, it returns True.
If the string does not start with the specified prefix, it returns False.
text = "Python is easy to learn." result = text.startswith('is easy') # Return False print(result) result = text.startswith('Python is') # Returns True print(result) result = text.startswith('Python is easy to learn.') # Returns True print(result)
When running the program, the output is:
False True True
text = "Python programming is easy." # Starting parameter: 7 # 'programming is easy.' string is searched result = text.startswith('programming is', 7) print(result) # start: 7, end: 18 # 'programming' string is searched result = text.startswith('programming is', 7, 18) print(result) result = text.startswith('program', 7, 18) print(result)
When running the program, the output is:
True False True
In Python, you can pass a tuple of prefixes to the startswith() method.
If the string starts with any item of the tuple, startswith() returns True. If not, it returns False
text = "programming is easy" result = text.startswith(('python', 'programming')) # Output True print(result) result = text.startswith(('is', 'easy', 'java')) # Output False print(result) # With start and end parameters # 'is easy' string is checked result = text.startswith(('programming', 'easy'), 12, 19) # Output False print(result)
When running the program, the output is:
True False False
If you need to check if a string ends with a specified suffix, you canin PythonUseendswith() method.