Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Python String startswith() method returns True if a string starts with the specified prefix (string). If not, it returns False.
Python String startswith() Method Syntax
Syntax: str.startswith(prefix, start, end)
Parameters:
- prefix: prefix ix nothing but a string that needs to be checked.
- start: Starting position where prefix is needed to be checked within the string.
- end: Ending position where prefix is needed to be checked within the string.
Return: Returns True if strings start with the given prefix otherwise returns False.
Python String startswith() Method Example
Here we will check if the string is starting with “Geeks” then it will return the True otherwise it will return false.
Python3
var
=
"Geeks for Geeks"
print
(var.startswith(
"Geeks"
))
print
(var.startswith(
"Hello"
))
Output:
True False
Example 1: Python String startswith() Method Without start and end Parameters
If we do not provide start and end parameters, then Python String startswith() method will check if the substring is present at the beginning of the complete String.
Python3
text
=
"geeks for geeks."
result
=
text.startswith(
'for geeks'
)
print
(result)
result
=
text.startswith(
'geeks'
)
print
(result)
result
=
text.startswith(
'for geeks.'
)
print
(result)
result
=
text.startswith(
'geeks for geeks.'
)
print
(result)
Output:
False True False True
Example 2: Python String startswith() Method With start and end Parameters
If we provide start and end parameters, then startswith() will check, if the substring within start and end starts matches with the given substring.
Python3
text
=
"geeks for geeks."
result
=
text.startswith(
'for geeks'
,
6
)
print
(result)
result
=
text.startswith(
'for'
,
6
,
9
)
print
(result)
Output:
True True
Example 3: Checking if String starts with one of many items using Python String startswith() Method
We can also pass a tuple instead of a string to match with in Python String startswith() Method. In this case, startswith() method will return True if the string starts with any of the item in the tuple.
Python3
string
=
"GeeksForGeeks"
res
=
string.startswith((
'geek'
,
'geeks'
,
'Geek'
,
'Geeks'
))
print
(res)
string
=
"apple"
res
=
string.startswith((
'a'
,
'e'
,
'i'
,
'o'
,
'u'
))
print
(res)
string
=
"mango"
res
=
string.startswith((
'a'
,
'e'
,
'i'
,
'o'
,
'u'
))
print
(res)
Output:
True True False
Like Article
Save Article
In this tutorial, we will learn about the Python String startswith() method with the help of examples.
The startswith()
method returns True
if a string starts with the specified prefix(string). If not, it returns False
.
Example
message = 'Python is fun'
# check if the message starts with Python
print(message.startswith('Python'))
# Output: True
Syntax of String startswith()
The syntax of startswith()
is:
str.startswith(prefix[, start[, end]])
startswith() Parameters
startswith()
method takes a maximum of three parameters:
- prefix — String or tuple of strings to be checked
- start (optional) — Beginning position where prefix is to be checked within the string.
- end (optional) — Ending position where prefix is to be checked within the string.
startswith() Return Value
startswith()
method returns a boolean.
- It returns True if the string starts with the specified prefix.
- It returns False if the string doesn’t start with the specified prefix.
Example 1: startswith() Without start and end Parameters
text = "Python is easy to learn."
result = text.startswith('is easy')
# returns False
print(result)
result = text.startswith('Python is ')
# returns True
print(result)
result = text.startswith('Python is easy to learn.')
# returns True
print(result)
Output
False True True
Example 2: startswith() With start and end Parameters
text = "Python programming is easy."
# start 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)
Output
True False True
Passing Tuple to startswith()
It’s possible to pass a tuple of prefixes to the startswith()
method in Python.
If the string starts with any item of the tuple, startswith()
returns True. If not, it returns False
Example 3: startswith() With Tuple Prefix
text = "programming is easy"
result = text.startswith(('python', 'programming'))
# prints True
print(result)
result = text.startswith(('is', 'easy', 'java'))
# prints False
print(result)
# With start and end parameter
# 'is easy' string is checked
result = text.startswith(('programming', 'easy'), 12, 19)
# prints False
print(result)
Output
True False False
If you need to check if a string ends with the specified suffix, you can use endswith() method in Python.
Синтаксис:
str.startswith(prefix[, start[, end]])
Параметры:
prefix
— объект поддерживающий итерацию (кортеж, символ или подстрока).start
—int
, индекс начала поиска, по умолчанию0
, необязательно.end
—int
, индекс конца поиска, по умолчаниюlen(str)
, необязательно.
Возвращаемое значение:
bool
,True
, если префиксprefix
совпал.
Описание:
Метод str.startswith()
возвращает True
, если строка str
начинается указанным префиксом prefix
, в противном случае возвращает False
.
Ограничивать поиск начала строки можно необязательными индексами start
и end
. В этом случае префикс будет искаться от начала среза.
- Префикс
prefix
также может быть кортежем префиксов для поиска. - Необязательные аргументы
start
иend
интерпретируются как обозначения среза строки и передаются как позиционные аргументы - При вызове без аргументов бросает исключение
TypeError
(требуется как минимум1
аргумент, передано0
).
Для поиска строк с требуемым окончанием используйте метод строки str.endswith()
.
Примеры поиска строк с указанным началом.
>>> x = 'начинается указанным префиксом prefix' >>> x.startswith('начин') # True >>> x.startswith('указанным') # False >>> x.startswith('указанным',11) # True # Есть список строк x = ['возвращает True', 'если строка str', 'начинается указанным', 'префиксом prefix'] # Нужны строки, которые начинаются на префиксы prefix = ('если', 'преф') for item in x: if item.startswith(prefix): print('YES =>', item) else: print('NOT =>', item) # NOT => возвращает True # YES => если строка str # NOT => начинается указанным # YES => префиксом prefix
Summary: in this tutorial, you’ll learn how to use the Python string startswith()
method to check if a string begins with another string.
Introduction to the Python string startswith() method
The startswith()
method returns True
if a string starts with another string. Otherwise, it returns False
.
The following shows the syntax of the startswith()
method:
str.startswith(prefix, [,start [,end ])
Code language: Python (python)
The startswith()
method accepts three parameters:
prefix
is a string or a tuple of strings to search for. Theprefix
parameter is mandatory.start
is the position that the method starts looking for theprefix
. Thestart
parameter is optional.end
is the position in the string that the method stops searching for theprefix
. Theend
parameter is also optional.
Note that the startswith()
method is case-sensitive. In other words, it will look for the prefix
case-sensitively.
Python string startswith() method examples
Let’s take some examples of using the string startswith()
method.
1) Using the startswith() method to check if a string begins with another string
The following example shows how to use the string startswith()
method to check if a string starts with another string:
s = 'Make it work, make it right, make it fast.'
result = s.startswith('Make')
print(result)
Code language: Python (python)
Output:
True
Code language: Python (python)
As mentioned earlier, the startswith()
method searches for a string case-sensitively. Therefore, the following example returns False
:
s = 'Make it work, make it right, make it fast.'
result = s.startswith('make')
print(result)
Code language: Python (python)
Output:
False
Code language: Python (python)
2) Using the startswith() method with a tuple
The following example uses the startswith()
method to check if a string starts with one of the strings in a tuple:
s = 'Make it work, make it right, make it fast.'
result = s.startswith(('Make','make'))
print(result)
Code language: PHP (php)
Output:
True
Code language: PHP (php)
3) Using the startswith() method with the start parameter
The following example illustrates how to use the startswith()
method to check if the string starts with the word make in lowercase starting from position 14:
s = 'Make it work, make it right, make it fast.'
result = s.startswith('make', 14)
print(result)
Code language: Python (python)
Output:
True
Code language: Python (python)
Summary
- Use the Python string
startswith()
method to determine if a string begins with another string.
Did you find this tutorial helpful ?
The Python startswith()
function checks if a string starts with a specified substring. Python endswith()
checks if a string ends with a substring. Both functions return True
or False
.
Often when you’re working with strings while programming, you may want to check whether a string starts with or ends with a particular value.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
For example, if you’re creating a program that collects a user’s phone number, you may want to check if the user has specified their country code. Or perhaps you’re creating a program that checks if a user’s name ends in e
for a special promotion your arcade is doing.
That’s where the built-in functions startswith()
and endswith()
come in. startswith()
and endswith()
can be used to determine whether a string starts with or ends with a specific substring, respectively.
This tutorial will discuss how to use both the Python startswith()
and endswith()
methods to check if a string begins with or ends with a particular substring. We’ll also work through an example of each of these methods being used in a program.
String Index Refresher
Before talk about startsWith and endsWith, we should take some time to refresh our knowledge on python string index.
A string is a sequence of characters such as numbers, spaces, letters, and symbols. You can access different parts of strings in the same way that you could with lists.
Every character in a string has an index value. The index is a location where the character is in the string. Index numbers start with 0. For example, here’s the string Python Substrings
with index numbers:
P | y | t | h | o | n | S | u | b | s | t | r | i | n | g | s | |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
The first character in the string is P
with an index value of 0. Our last character, s
, has an index value of 16. Because each character has its own index number, we can manipulate strings based on where each letter is located.
Python Startswith
The startswith()
string method checks whether a string starts with a particular substring. If the string starts with a specified substring, the startswith()
method returns True; otherwise, the function returns False.
Here’s the syntax for the Python startswith()
method:
string_name.startswith(substring, start_pos, end_pos)
The startswith()
with method takes in three parameters, which are as follows:
- substring is the string to be checked within the larger string (required)
- start_pos is the start index position at which the search for the substring should begin (optional)
- end_pos is the index position at which the search for the substring should end (optional)
The substring parameter is case sensitive. So, if you’re looking for s
in a string, it will only look for instances of a lowercase s
. If you want to look for an uppercase S
, you’ll need to specify that character. In addition, remember that index positions in Python start at 0
, which will affect the start_pos
and end_pos
parameters.
Let’s walk through an example to showcase the startswith()
method in action.
Say that we are an arcade operator and we are running a special promotion. Every customer whose name starts with J
is entitled to 200 extra tickets for every 1000 tickets they win at the arcade. To redeem these tickets, a customer must scan their arcade card at the desk, which runs a program to check the first letter of their name.
Here’s the code we could use to check whether the first letter of a customer’s name is equal to J
:
customer_name = "John Milton" print(customer_name.startswith("J"))
Our code returns: True. On the first line of our code, we define a variable called customer_name
which stores the name of our customer. Then, we use startswith()
to check whether the “customer_name
” variable starts with J
. In this case, our customer’s name does start with J
, so our program returns True.
If you don’t specify the start_pos
or end_pos
arguments, startswith()
will only search for the substring you have specified at the beginning of the string.
Now, let’s say that we are changing our promotion and only people whose name contains an s
between the second and fifth letters of their full name. We could check to see if a customer’s full name contained an s
between the second and fifth letters of their full name using this code:
customer_name = "John Milton" print(customer_name.startswith("s", 1, 5))
Our code returns: False. In our code, we have specified both a start_pos
and an end_pos
parameter, which are set to 1 and 5, respectively. This tells startswith()
only to search for the letter s
between the second and fifth characters in our string (the characters with an index value between 1 and 5).
Python Endswith
The endswith()
string formatting method can be used to check whether a string ends with a particular value. endswith()
works in the same way as the startswith()
method, but instead of searching for a substring at the start of a string, it searches at the end.
Here’s the syntax for the endswith()
method:
string_name.endswith(substring, start_pos, end_pos)
The definitions for these parameters are the same as those used with the startswith()
method.
Let’s explore an example to showcase how the endswith()
method can be used in Python. Say we are running an airline and we want to process a refund on a customer’s credit card. To do so, we need to know the last four digits of their card number so that we can check it against the one that we have on file.
Here’s an example of endswith()
being used to check whether the four digits given by a customer match those on file:
on_file_credit_card = '4242 4242 4242 4242' matches = on_file_credit_card.endswith('4242') print(matches)
Our program returns: True. In this case, our customer gave us the digits 4242
. We used the endswith()
method to verify whether those numbers matched the ones that we had on file. In this case, the credit card on-file ended with 4242
, so our program returned True.
We could also use the optional start_pos
and end_pos
arguments to search for a substring at a certain index position.
«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»
Venus, Software Engineer at Rockbot
Say we are operating a cafe and we have a string that stores everything a customer has ordered. Our chef wants to know whether an order contains Ham Sandwich
, and knows the length of our string is 24. The last five characters of our string contain ORDER
. So, we want to skip over the first five characters in our string.
We could perform this search using the following code:
order = "ORDER Latte Ham Sandwich" includes_ham_sandwich = order.endswith("Ham Sandwich", 0, 19) print(includes_ham_sandwich)
Our code returns: True
.
In our example, we specify Ham Sandwich
as our substring parameter.
Then, we specify 0
as the start_pos
parameter because we are going to be using the end_pos
parameter and start_pos
cannot be blank when we use end_pos
. We specify 19 as our end_pos
argument because the last five characters of our string are ORDER
, and the character before that is a whitespace.
Our string ends in Ham Sandwich
, so our program returns True. If our string did not end in Ham Sandwich
, the suffix otherwise returns False.
Python Endswith with Lists
In addition, endswith()
can take in a list or a tuple as the substring
argument, which allows you to check whether a string ends with one of multiple strings. Say we are creating a program that checks if a file name ends in either .mp3
or .mp4
. We could perform this check using the following code:
potential_extensions = ['.mp3', '.mp4'] file_name = 'music.mp3' print(file_name.endswith(potential_extensions))
Our code returns: True. In this example, we have created an array called potential_extensions
that stores a list of file extensions. Then, we declared a variable called file_name
which stores the name of the file whose extension we want to check.
Finally, we use the endswith()
method to check if our string ends in any of the extensions in our potential_extensions
list. In this case, our file name ends in .mp3
, which is listed in our potential_extensions
list, so our program returns True.
Conclusion
The startswith()
and endswith()
methods can be used to check whether a Python string begins with or ends with a particular substring, respectively. Each method includes optional parameters that allow you to specify where the search should begin and end within a string.
This tutorial discussed how to use both the startswith()
and endswith()
methods, and explored a few examples of each method in action. Now you’re ready to check if strings start with or end with a substring using the startswith()
and endswith()
methods like an expert.