Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

How to Get a Substring of a String in Python

Use slicing, negative indexes, steps and other tools to cut parts out of a string.

How-To Guides2 min read5 screenshots

Strings in Python

A string is a sequence of characters, and each character has an index. The first has index 0.

my_string = "Hello, world!"

A substring is a part of a string. In Python you get substrings with slicing.

Slice syntax

string[start:end:step]
  • start (optional) is the first index, included.
  • end (optional) is the last index, excluded.
  • step (optional) is the interval between characters.

Examples

Basic slicing

my_string = "Hello, World!"
substring = my_string[0:5]
print(substring)
Basic string slicing

Output: Hello

Leave out the start and the end

my_string = "Hello, World!"
print(my_string[:5])    # from the start
print(my_string[7:])    # to the end
print(my_string[:])     # a copy of the whole string
Omitting the start and the end

Output:

Hello
World!
Hello, World!

Negative indexes

A negative index counts from the end. -1 is the last character.

my_string = "Hello, World!"
substring = my_string[-6:-1]
print(substring)
Slicing with negative indexes

Output: World

Use a step

my_string = "Hello, World!"
print(my_string[::2])
Slicing with a step

Output: Hlo ol!

Reverse a string with a step of -1:

print(my_string[::-1])

Output: !dlroW ,olleH

Find a specific pattern

Use find() to get the position, then slice:

text = "Contact: support@example.com for help"
start = text.find("support")
end = text.find(" for")
print(text[start:end])
Extracting a specific pattern

Output: support@example.com

For harder patterns use regular expressions:

import re
match = re.search(r"[\w.]+@[\w.]+", text)
print(match.group())

Useful string methods

  • text.split(",") splits a string into a list.
  • text.partition(":") splits at the first match into 3 parts.
  • text.startswith("Hel") and text.endswith("!") test the ends.
  • text.index("W") is like find() but raises an error when nothing is found.
  • "World" in text tests if a substring exists.

Tips

  • Slicing never raises an error for indexes out of range. It just returns what exists.
  • Strings are immutable: slicing makes a new string.

Quick recap

  • s[start:end] cuts a substring, s[-3:] takes the last 3 characters, s[::-1] reverses.