Exploring the endswith() method

Exploring the endswith() method


A futuristic coding background with a futuristic neon text and bright popping frame. Text reads: the endswith() method. Check the ending of a string or slice specifically

Today I learned about the .endswith() method in Python.

It was something really really cool and new and it was really interesting to use.

It basically is a really really cool way to check if a string ends with the same thing it is being checked against or not. So how would we use it exactly? Well it takes 3 arguments: one compulsory, two optional:

string.endswith(suffix[, start [, end]])
  • So you can either just have the suffix and see if the value is the same at the end of the string:
name_string = "susanna"

name_string.endswith("anna") -> returns True
  • Or you can slice, let me try
name_string = "susanna"

name_string.endswith("san", 2, 5) -> returns True
  • As with all slicing, please remember that the ending condition is +1 of the index of the last character you would like to include, and the start INCLUDES the starting character that you want to include, so the exact index of that character. It's just like any regular list or string slicing.
  • Btw, you can slice tuples like you can slice lists and strings, but not dictionaries.

Comments