Python String startswith() Method
The startswith() function checks if a string starts with a prefix. If so, startswith() will return the boolean True, otherwise it will return the boolean false.
How to formulate it like this:
string.startswith(prefix, start, end)
prefix: A word, string, or tuple that must be checked
start: [Optional] Start the index where the search starts.
end: [optional] The end of the index where the search stops.
Return value: Returns a boolean value that is either true or false.
In the following example we will check if a string starts with "learn". If it is, startswith() will return the boolean True, otherwise it will return the boolean false.
Example:
# Define a variable
string1 = "learn python with ahmad obaid"
# startswith function call
print(string1.startswith("learn")) # returns True
# Define a variable
string2 = "Hello Python"
# startswith function call
print(string2.startswith("learn")) # returns False
The output will be:
True
False
In the following example we will check if the given word is between the starting indexundefined Finally, if it is, the startswith() function will return the boolean True, and if it is not, it will return the boolean false.
Example:
# startswith function call
string = "learn python with ahmad obaid"
# startswith function call
print(string.startswith('python' , 6)) # returns True
# startswith function call
print(string.startswith('ahmad' , 18, 23)) # returns True
# startswith function call
print(string.startswith('learn' , 0, 6)) # returns True
The output will be:
True
True
True
In the following example we will check if the string contains a tuple. That is, if the string starts with any element of the tuple, the startswith() function will return the boolean value True, and if it is otherwise, it will return the boolean value false
Example:
# Define a variable
string = "learn python with ahmad obaid"
# startswith function call
result = string.startswith(( 'Hello', 'python', 'learn', 'mango')) # returns True
# Print the result
print(result)
# Define a variable
string = "ahmad"
# startswith function call
result = string.startswith(('e', 'a', 'i', 'o', 'u')) # returns True
# Print the result
print(result)
# Define a variable
string = "python"
# startswith function call
result = string.startswith(('e', 'a', 'i', 'o', 'u')) # returns False
# Print the result
print(result)
The output will be:
True
True
False
External sources:
Built-in functions - official Python documentation
If you have any questions or concerns, leave them in the comments
Tags
Python python data types Python String string methods python python string startswith method String comparison functions in Python
Share page
About author
Ahmed Obaid
Hello, I am Ahmed Obaid, an Egyptian Arabic programmer. I would like to put my experiences learning Python on this site So that it will be a reference for you and me as well.
Sign up to leave a comment