To find a string that starts with something(prefix), use the Python String startswith() function.
How to Check Start Character of String in Python
To check the start character of a string in Python, use the startswith() function. The string startswith() is a built-in function that checks whether the string starts with a given prefix. Otherwise, it returns False. In addition, it optionally restricts the matching with the given indices at the start and end.
Python String startswith() returns true if found matching string otherwise false.
Syntax
str.startswith(prefix, beg=0,end=len(string));
Parameters
- prefix − This is the string to be checked.
- beg − This is the optional parameter to set a start index of the matching boundary.
- end − This is the optional parameter to the end start index of the matching limit.
Let’s see the example.
// app.py strA = 'Hello AppDividend' print(strA.startswith('App', 6))
In the above code, we have checked for the prefix App, starting from a 6th index in the strA string.
So, the output will be true.
Here, one thing to note is that the prefix is case-sensitive. So, if you find an app, then it will give a false output. It will only give true if the substring is App and starts with the 6th index.
See the output.
Let’s see the following scenario.
// app.py strA = 'Hello AppDividend' print(strA.startswith('app', 6))
Here, we are checking for the app and not App. So the startswith() function is case sensitive, which will give us the false in the output.
So, the startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False.
That’s it for this tutorial.