Introduction to Slicing in Python

What is the output of this code snippet?

 

word = "galaxy"
print(word[:-2] + word[-2:])

This puzzle introduces the important concept of slicing. Slicing is one of the most popular features in Python. Understand the term and concept of slicing and you are at least among the intermediate Python programmers.

Slicing, like indexing, retrieves specific characters from a sequence such as a string. But while indexing retrieves only a single character, slicing retrieves a whole substring within an index range.

Use the bracket notation for slicing with the start and end position identifiers. For example, word[i:j] returns the substring starting from index i (included) and ending in index j (excluded).

You can also skip the position identifier before or after the slicing colon. This indicates that the slice starts from the first or last position, respectively. For example, word[:i] + word[i:] returns the same string as word.

 


Are you a master coder?
Test your skills now!

 

Related Video

Solution

galaxy

 

Leave a Comment