Slicing Strings

Slicing in Python allows you to extract a portion of a string using a slice operator [start:stop:step]. This is useful for accessing substrings or reversing strings.

Basic Slicing:

Python
text = "Hello, World!"

# Slicing to get "Hello"
slice_hello = text[0:5]

# Slicing to get "World"
slice_world = text[7:12]

print(slice_hello)  # Output: Hello
print(slice_world)  # Output: World

Omitting Indices:

If you omit the start index, Python starts slicing from the beginning of the string. If you omit the stop index, Python slices to the end of the string.

Python
text = "Python Programming"

# From start to index 6 (exclusive)
print(text[:6])  # Output: Python

# From index 7 to end
print(text[7:])  # Output: Programming

Using Step in Slicing:

The step parameter allows you to skip characters in the string:

Python
text = "abcdef"

# Slice every second character
print(text[::2])  # Output: ace

# Reverse the string
print(text[::-1])  # Output: fedcba

Slicing is a powerful tool that lets you work with parts of strings efficiently.