Today we will learn how to check if there is a string start with specific letter or word. We will use startswith()
function on a string. This built-in function will return value as booleean, true as the result is confirm start with the given value, otherwise false. This short tutorial we given example Below examples would help guide you to approch the result.
startswith() - checks if a string starts with a specified substring.
str.startswith(prefix, start_index, end_index): boolean
Return Value: Returns boolean. True if str start with specific prefix if not return False.
To understand more clearly, I will explain about index value. In every programming languages, characters in a string have own index value. The index always start with 0 (Zero) located where character is in string. Let's see example below:
String | E | a | t | C | a | k | e | |
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
Position | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
You can see example above letter E is in index 0 and all index are 7 but if count as string length there are 8 characters.
Parameters | Type | Description |
---|---|---|
prefix | String , Tuple (Required) | String or Tuple data to be check with str |
start_pos | Integer (Optional) | Start index to be check string with prefix |
end_pos | Integer (Optional) | End index to be check string with prefix |
Example #1 - Using startswith() with String without optional parameters
text = "learn python at cambotutorial"
bool = text.startswith("lea")
print(bool)
Output:
True
Example #2 - Using startswith() with Tuple without optional parameters
Using parameter as Tuple value.
text = "learn python at cambotutorial"
bool = text.startswith(("tool","lea"))
print(bool)
Output:
True
It's return true because one of tuple value is match.
Example #3 - Using startswith() with optional parameters
text = "learn python at cambotutorial"
# find is text start with lea by start from index 1 "earn python at cambotutorial"
bool = text.startswith("lea",1)
#False
print(bool)
Output:
False
It's return false because start from index 1 till end of index which is "earn python at cambotutorial" not start with lea
Example #4 - Using startswith() with optional parameters
text = "learn python at cambotutorial"
# find is text start with lea by start from index 0 "lear"
bool = text.startswith("lea",0,4)
print(bool)
Output:
True
It's return true because start from index 0 until index 4 which is "learn" start with lea
Hope you will learn with this article, if want to check string end with specific letter, I have wrote an article using endswith()
in Python.
You might Also Like:
Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him