PyPyPath

Module 4: Strings in Python

Slicing Strings

Slicing means cutting out a piece of a string — a substring. You use [start:end] where end is not included.

About 10 minutes

Basic slicing [start:end]

Example code
word = "DataScience"
print(word[0:4])   # Data
print(word[4:11])  # Science
print(word[:4])    # Data (from start)
print(word[4:])    # Science (to end)
word[0:4] → characters at 0,1,2,3

Start 0

Include

Middle

1, 2, 3

End 4

Stop before

Step slicing [start:end:step]

Example code
text = "Python"
print(text[::2])   # Pto  (every 2nd letter)
print(text[::-1])  # nohtyP (reverse)
Practice

From email = "user@mail.com", slice the username and domain parts.

Key takeaways

  • [start:end] gives characters from start up to (not including) end.
  • Omit start or end to slice from beginning or to the end.
  • [::-1] reverses a string.

Quick check: Slicing Strings

Question 1 of 2

What is "Python"[0:3]?