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)

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

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)

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

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])

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")andtext.endswith("!")test the ends.text.index("W")is likefind()but raises an error when nothing is found."World" in texttests 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.