Slicing in Python

One of the core features of the Python language is slicing, as it appears in many commands.

What is slicing? The term comes from the English word "to slice" (to cut into pieces). It involves dividing an object into numbered units in a sequential order. This can apply to both lists and characters in a string.
an example of slicing a string

    How to Use Slicing in Python

    Consider an alphanumeric string containing the name "Andrea Minini."

    This string consists of 13 characters.

    Using slicing, the string is treated as a sequence of thirteen elements, each with its own position.

    Position 0 marks the start of the string.

    slicing in Python

    With this indexing, you can extract any substring by specifying its start and end positions.

    For example, to extract the substring "rea" using slicing, you would write (3:6).

    how to extract a substring in Python

    Example 1

    To extract and display the substring from a variable, you would use the following script:

    nome="andrea minini"
    print(nome[3:6])

    The output is:

    rea

    Slicing can also be done in reverse.

    In this case, position -1 indicates the end of the last character of the string, and the numbering is negative, going from right to left.

    reverse slicing

    To extract the same substring "rea" in this case, you would write (-10:-7).

    The first position on the left always indicates the start of the substring.

    how to extract a substring from a string in Python using slicing

    Example 2

    To extract and display the substring, you would use the following script:

    nome="andrea minini"
    print(nome[-10:-7])

    The output remains:

    rea

    In these examples, we used a string.

    However, slicing can also be applied to a list. In this case, the positions would refer to the elements of the list.

    The principle behind slicing remains the same.

     

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Strings in Python

    FAQ