How do I get a substring of a string in Python?

To get a substring of a string in Python, you can use string slicing with the syntax [start:end:step]. Here’s how it works:

Basic Syntax

substring = string[start : end]  # Characters from index `start` (inclusive) to `end` (exclusive)

Examples

1. Extract “World” from “Hello, World!”

s = "Hello, World!"
print(s[7:12])  # Output: "World" (indices 7 to 11)

2. First 5 Characters

print(s[:5])     # Output: "Hello" (indices 0 to 4)

3. From Index 7 to End

print(s[7:])     # Output: "World!" (indices 7 to end)

4. Last 6 Characters

print(s[-6:])    # Output: "World!" (last 6 characters)

Key Rules

  • Indices start at 0.
  • start is inclusive, end is exclusive.
  • Omit start to start from the beginning (s[:end]).
  • Omit end to go to the end (s[start:]).
  • Use negative indices to count from the end (-1 = last character).

Advanced: Step Value

Add a third parameter (step) to skip characters:

print(s[::2])    # Every 2nd character: "Hlo ol!"
print(s[::-1])   # Reverse the string: "!dlroW ,olleH"

Common Use Cases

Use CaseExampleOutput
First n characterss[:5]"Hello"
Last n characterss[-6:]"World!"
From index i to js[7:12]"World"
Every k-th characters[::2]"Hlo ol!"
Reverse a strings[::-1]"!dlroW ,olleH"

Edge Cases

  • If start > end, returns an empty string ("") unless using a negative step.
  • Out-of-range indices are handled gracefully (e.g., s[0:100] returns the entire string).

Summary

Use slicing to extract substrings by specifying start, end, and optional step. Python’s flexible syntax handles most use cases intuitively!

Leave a Reply

Your email address will not be published. Required fields are marked *