String Slicing in Python

The String slicing allows you to extract a part of a string using indices.
• Python strings are sequences, so each character has an index.
• Indexing starts from 0 (first character) and can be negative (from the end).
• Slice returns a new string, original string is unchanged.

Syntax string[start:stop:step]

The function has the following parameters:

The slice includes characters from start up to stop-1 in steps of step.

Example: Basic Slicing.

Python

text = "Hello World"
print(text[0:5])   # Output: Hello
# Characters from index 0 to 4

Example: Omitting start or stop.

Python

print(text[:5])    # Output: Hello   (start defaults to 0)
print(text[6:])    # Output: World   (stop defaults to end of string)
print(text[:])     # Output: Hello World  (entire string)

Example: Using Negative Indices.

Python

print(text[-5:])    # Output: World (last 5 characters)
print(text[:-6])    # Output: Hello (everything except last 6 characters)

Example: Using Step.

Python

text = "Hello World"
print(text[::2])    # Output: HloWrd (every 2nd character)
print(text[1::2])   # Output: el ol   (every 2nd character starting from index 1)

Example: Reversing a String.

Python

print(text[::-1])   # Output: dlroW olleH
# step=-1 reverses the string