What is the pythonic way of writing the following code?
extensions = ['.mp3','.avi']
file_name = 'test.mp3'
for extension in extensions:
if file_name.endswith(extension):
#do stuff
I have a vague memory that the explicit declaration of the for
loop can be avoided and be written in the if
condition. Is this true?
BiGYaN
6,9045 gold badges30 silver badges43 bronze badges
asked Aug 21, 2013 at 8:02
1
Though not widely known, str.endswith also accepts a tuple. You don’t need to loop.
>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True
Gringo Suave
29.3k6 gold badges88 silver badges75 bronze badges
answered Aug 21, 2013 at 8:03
6
Just use:
if file_name.endswith(tuple(extensions)):
Kenly
23.1k7 gold badges44 silver badges59 bronze badges
answered Aug 21, 2013 at 8:03
Jon ClementsJon Clements
137k32 gold badges244 silver badges277 bronze badges
1
another way which can return the list of matching strings is
sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']
answered Dec 31, 2018 at 9:08
Akash SinghAkash Singh
3524 silver badges5 bronze badges
1
There is two ways: regular expressions and string (str) methods.
String methods are usually faster ( ~2x ).
import re, timeit
p = re.compile('.*(.mp3|.avi)$', re.IGNORECASE)
file_name = 'test.mp3'
print(bool(t.match(file_name))
%timeit bool(t.match(file_name)
792 ns ± 1.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
file_name = 'test.mp3'
extensions = ('.mp3','.avi')
print(file_name.lower().endswith(extensions))
%timeit file_name.lower().endswith(extensions)
274 ns ± 4.22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
answered Mar 3, 2018 at 21:52
Igor AIgor A
3113 silver badges9 bronze badges
I just came across this, while looking for something else.
I would recommend to go with the methods in the os
package. This is because you can make it more general, compensating for any weird case.
You can do something like:
import os
the_file = 'aaaa/bbbb/ccc.ddd'
extensions_list = ['ddd', 'eee', 'fff']
if os.path.splitext(the_file)[-1] in extensions_list:
# Do your thing.
answered Mar 13, 2018 at 9:00
XxxoXxxo
1,7241 gold badge15 silver badges24 bronze badges
I have this:
def has_extension(filename, extension):
ext = "." + extension
if filename.endswith(ext):
return True
else:
return False
answered Apr 7, 2017 at 8:34
1
Another possibility could be to make use of IN statement:
extensions = ['.mp3','.avi']
file_name = 'test.mp3'
if "." in file_name and file_name[file_name.rindex("."):] in extensions:
print(True)
answered Apr 23, 2018 at 13:09
NeverHopelessNeverHopeless
11k4 gold badges34 silver badges56 bronze badges
1
While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string ends with any of the matching strings. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using filter() + endswith() The combination of the above function can help to perform this particular task. The filter method is used to check for each word and endswith method tests for the suffix logic at target list.
Python3
test_string
=
"GfG is best"
suff_list
=
[
'best'
,
'iss'
,
'good'
]
print
(
"The original string :"
+
str
(test_string))
res
=
list
(
filter
(test_string.endswith, suff_list)) !
=
[]
print
(
"Does string end with any suffix list sublist ? :"
+
str
(res))
Output
The original string :GfG is best Does string end with any suffix list sublist ? :True
Time Complexity : O(n)
Space Complexity : O(n)
Method #2 : Using endswith() As an improvement to the above method, it is not always necessary to include filter method for comparison. This task can be handled solely by supplying a suffix check list as an argument to endswith method as well.
Python3
test_string
=
"GfG is best"
suff_list
=
[
'best'
,
'iss'
,
'good'
]
print
(
"The original string :"
+
str
(test_string))
res
=
test_string.endswith(
tuple
(suff_list))
print
(
"Does string end with any suffix list sublist ? :"
+
str
(res))
Output
The original string :GfG is best Does string end with any suffix list sublist ? :True
Time Complexity : O(n)
Space Complexity : O(1)
Method #3 : Using split().Splitting the given string and comparing every string of list for matching suffix
Python3
res
=
False
test_string
=
"GfG is best"
suff_list
=
[
'best'
,
'iss'
,
'good'
]
print
(
"The original string : "
+
str
(test_string))
x
=
test_string.split()
for
i
in
suff_list:
if
(x[
-
1
]
=
=
i):
res
=
True
print
(
"Does string end with any suffix list sublist ? : "
+
str
(res))
Output
The original string : GfG is best Does string end with any suffix list sublist ? : True
Time Complexity : O(n)
Space Complexity : O(1)
Method #4 : Using split() and in operator
Python3
res
=
False
test_string
=
"GfG is best"
suff_list
=
[
'best'
,
'iss'
,
'good'
]
print
(
"The original string : "
+
str
(test_string))
x
=
test_string.split()
if
x[
-
1
]
in
suff_list:
res
=
True
print
(
"Does string end with any suffix list sublist ? : "
+
str
(res))
Output
The original string : GfG is best Does string end with any suffix list sublist ? : True
Time Complexity : O(n)
Space Complexity : O(1)
Method #5 : Using find() and len() methods
Python3
res
=
False
test_string
=
"GfG is best"
suff_list
=
[
'best'
,
'iss'
,
'good'
]
print
(
"The original string : "
+
str
(test_string))
for
i
in
suff_list:
a
=
test_string.find(i)
b
=
len
(test_string)
-
len
(i)
if
(a
=
=
b):
res
=
True
print
(
"Does string end with any suffix list sublist ? : "
+
str
(res))
Output
The original string : GfG is best Does string end with any suffix list sublist ? : True
Time complexity: O(n * m)
Space complexity: O(1)
Method #6 : Using any()
The any function in Python returns True if any element in an iterable is True, and False otherwise. In this approach, we use a list comprehension to generate a list of boolean values, where each value is True if the test string ends with the current suffix in the list, and False otherwise. The any function is then used to check if any element in the list is True.
Python3
test_string
=
"GfG is best"
suffix_list
=
[
'best'
,
'iss'
,
'good'
]
print
(
"The original string :"
+
str
(test_string))
result
=
any
(test_string.endswith(suffix)
for
suffix
in
suffix_list)
print
(
"Does string end with any suffix list sublist ? :"
+
str
(result))
Output
The original string :GfG is best Does string end with any suffix list sublist ? :True
Time complexity: O(n), where n is the length of the suffix list
Auxiliary space: O(1)
Method 7: using operator.countOf() method
Python3
import
operator as op
res
=
False
test_string
=
"GfG is best"
suff_list
=
[
'best'
,
'iss'
,
'good'
]
print
(
"The original string : "
+
str
(test_string))
x
=
test_string.split()
if
op.countOf(suff_list, x[
-
1
]) >
0
:
res
=
True
print
(
"Does string end with any suffix list sublist ? : "
+
str
(res))
Output
The original string : GfG is best Does string end with any suffix list sublist ? : True
Time Complexity: O(N)
Auxiliary Space : O(1)
Method 8: Using regular expressions
Python3
import
re
test_string
=
"GfG is best"
suffix_list
=
[
'best'
,
'iss'
,
'good'
]
print
(
"The original string : "
+
str
(test_string))
flag
=
False
for
suffix
in
suffix_list:
match
=
re.search(r
'{}$'
.
format
(suffix), test_string)
if
match:
flag
=
True
break
print
(
"Does string end with any suffix list sublist ? : "
+
str
(flag))
Output
The original string : GfG is best Does string end with any suffix list sublist ? : True
Time Complexity: O(N)
Auxiliary Space : O(1)
Method#9: Using Recursive method.
Python3
def
check_suffix(string, suffix_list):
if
not
string:
return
False
words
=
string.split()
if
not
words:
return
False
if
words[
-
1
]
in
suffix_list:
return
True
return
check_suffix(
" "
.join(words[:
-
1
]), suffix_list)
res
=
False
test_string
=
"GfG is best"
suff_list
=
[
'best'
,
'iss'
,
'good'
]
print
(
"The original string : "
+
str
(test_string))
res
=
check_suffix(test_string, suff_list)
print
(
"Does string end with any suffix list sublist ? : "
+
str
(res))
Output
The original string : GfG is best Does string end with any suffix list sublist ? : True
Time Complexity: O(n)
Auxiliary Space: O(n)
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.
In this tutorial, we will learn about the Python String endswith() method with the help of examples.
The endswith()
method returns True
if a string ends with the specified suffix. If not, it returns False
.
Example
message = 'Python is fun'
# check if the message ends with fun
print(message.endswith('fun'))
# Output: True
Syntax of String endswith()
The syntax of endswith()
is:
str.endswith(suffix[, start[, end]])
endswith() Parameters
The endswith()
takes three parameters:
- suffix — String or tuple of suffixes to be checked
- start (optional) — Beginning position where suffix is to be checked within the string.
- end (optional) — Ending position where suffix is to be checked within the string.
Return Value from endswith()
The endswith()
method returns a boolean.
- It returns True if a string ends with the specified suffix.
- It returns False if a string doesn’t end with the specified suffix.
Example 1: endswith() Without start and end Parameters
text = "Python is easy to learn."
result = text.endswith('to learn')
# returns False
print(result)
result = text.endswith('to learn.')
# returns True
print(result)
result = text.endswith('Python is easy to learn.')
# returns True
print(result)
Output
False True True
Example 2: endswith() With start and end Parameters
text = "Python programming is easy to learn."
# start parameter: 7
# "programming is easy to learn." string is searched
result = text.endswith('learn.', 7)
print(result)
# Both start and end is provided
# start: 7, end: 26
# "programming is easy" string is searched
result = text.endswith('is', 7, 26)
# Returns False
print(result)
result = text.endswith('easy', 7, 26)
# returns True
print(result)
Output
True False True
Passing Tuple to endswith()
It’s possible to pass a tuple suffix to the endswith()
method in Python.
If the string ends with any item of the tuple, endswith()
returns True. If not, it returns False
Example 3: endswith() With Tuple Suffix
text = "programming is easy"
result = text.endswith(('programming', 'python'))
# prints False
print(result)
result = text.endswith(('python', 'easy', 'java'))
#prints True
print(result)
# With start and end parameter
# 'programming is' string is checked
result = text.endswith(('is', 'an'), 0, 14)
# prints True
print(result)
Output
False True True
If you need to check if a string starts with the specified prefix, you can use startswith() method in Python.
Python string endswith() is a built-in method that returns True if the end of the string is with the specified suffix; otherwise, False. If the start and end index is not provided, then by default, it takes 0 and length-1 as starting and ending indexes. It does not include the ending index while in search.
Syntax
string.endswith(suffix, start, end)
Arguments
Suffix: This is part of the string for which we are checking if the string is ending with that part or not.
Start: The suffix starts from here; it is optional.
End: The suffix ends here; it is optional.
Example 1
string = "Hello I am a string and I am ending with = end"
result = string.endswith("end")
result1 = string.endswith("END")
print("Comparing it with right suffix so output: ",result)
print("Comparing it with wrong suffix so output: ",result1)
Output
Comparing it with right suffix so output: True
Comparing it with the wrong suffix so output: False
Example 2
string = "This is a string and is awesome"
right_suf = "some"
wrong_suf = "some!"
print(string.endswith(right_suf, 28, 31))
print(string.endswith(wrong_suf, 28, 31))
Output
That’s it.