a slice of a string, tuple, or list is: in python

You can use slicing to extract a portion of a string, tuple, or list in Python. Slicing allows you to select a contiguous section of the sequence by specifying a start and stop index along with an optional step value.

Here is the syntax for slicing:

main.py
sequence[start:stop:step]
26 chars
2 lines
  • start: Optional. Starting index of the slice. Defaults to 0 if not provided.
  • stop: Ending index (exclusive) of the slice. Defaults to the length of the sequence if not provided.
  • step: Optional. Step size of the slice. Defaults to 1 if not provided.

Here are some examples of slicing in Python:

main.py
# slicing a string
s = "Hello, World!"
print(s[0])     # H
print(s[7:12])  # World
print(s[:5])    # Hello
print(s[7:])    # World!
print(s[::2])   # Hlo ol!
print(s[::-1])  # !dlroW ,olleH

# slicing a list
L = [1, 2, 3, 4, 5]
print(L[0])     # 1
print(L[2:4])   # [3, 4]
print(L[:3])    # [1, 2, 3]
print(L[3:])    # [4, 5]
print(L[::2])   # [1, 3, 5]
print(L[::-1])  # [5, 4, 3, 2, 1]

# slicing a tuple
t = (1, 2, 3, 4, 5)
print(t[0])     # 1
print(t[2:4])   # (3, 4)
print(t[:3])    # (1, 2, 3)
print(t[3:])    # (4, 5)
print(t[::2])   # (1, 3, 5)
print(t[::-1])  # (5, 4, 3, 2, 1)
587 chars
27 lines

gistlibby LogSnag