0
0
PythonHow-ToBeginner · 3 min read

How to Slice a String in Python: Simple Syntax and Examples

In Python, you slice a string using the string[start:end:step] syntax, where start is the index to begin, end is the index to stop (exclusive), and step is how many characters to skip. This extracts a part of the string easily and works with positive or negative indexes.
📐

Syntax

The basic syntax for slicing a string is string[start:end:step].

  • start: The index where the slice starts (inclusive). Defaults to 0 if omitted.
  • end: The index where the slice ends (exclusive). Defaults to the string's length if omitted.
  • step: The step size or stride between characters. Defaults to 1 if omitted.

Negative indexes count from the end of the string, and negative steps reverse the slice direction.

python
s = "Hello, world!"

# slice syntax examples
print(s[0:5])    # 'Hello'
print(s[7:12])   # 'world'
print(s[:5])     # 'Hello' (start defaults to 0)
print(s[7:])     # 'world!' (end defaults to length)
print(s[::2])    # 'Hlo ol!'
print(s[::-1])   # '!dlrow ,olleH' (reversed string)
Output
Hello world Hello world! Hlo ol! !dlrow ,olleH
💻

Example

This example shows how to extract parts of a string using slicing, including reversing the string and skipping characters.

python
text = "Python slicing"

# Extract 'Python'
part1 = text[0:6]

# Extract 'slicing'
part2 = text[7:]

# Extract every second character
part3 = text[::2]

# Reverse the string
part4 = text[::-1]

print(part1)
print(part2)
print(part3)
print(part4)
Output
Python slicing Pto icn gnicils nohtyP
⚠️

Common Pitfalls

Common mistakes when slicing strings include:

  • Using an end index that is out of range (Python handles this gracefully by stopping at the string end).
  • Forgetting that the end index is exclusive, so the character at end is not included.
  • Using a step of zero, which causes an error.
  • Confusing negative indexes and steps, which can reverse the slice.
python
s = "example"

# Wrong: step cannot be zero
# print(s[::0])  # This raises ValueError

# Right: use step 1 or other non-zero
print(s[::1])    # 'example'

# Wrong: expecting end index to be inclusive
print(s[0:3])    # 'exa' (not 'exam')

# Right: use end index one past last desired character
print(s[0:4])    # 'exam'
Output
example exa exam
📊

Quick Reference

SyntaxDescriptionExampleResult
s[start:end]Slice from start to end-1s[1:4]'ell' from 'Hello'
s[:end]Slice from start to end-1s[:3]'Hel'
s[start:]Slice from start to ends[2:]'llo'
s[::step]Slice whole string with steps[::2]'Hlo'
s[::-1]Reverse the strings[::-1]'olleH'
s[-3:-1]Slice using negative indexess[-3:-1]'ll'

Key Takeaways

Use the syntax string[start:end:step] to slice strings in Python.
The end index is exclusive, so the slice stops before this index.
Negative indexes count from the string's end, enabling flexible slicing.
A negative step reverses the string or slice direction.
Avoid using a step of zero as it causes an error.