Lesson 17 / 47

Slicing, Split & Join

Strings behave like sequences — slice them, break them apart, and glue them back.

Slicing text

A string can be sliced exactly like a list, since it's an ordered sequence of characters.

s = "Hello, Python"
print(s[7:])       # 'Python'
print(s[:5])       # 'Hello'
print(s[::-1])     # 'nohtyP ,olleH'

split() and join()

split() turns text into a list; join() does the reverse — glue a list into text with a separator.

csv_line = "apple,banana,cherry"
fruits = csv_line.split(",")
print(fruits)             # ['apple', 'banana', 'cherry']
print(" | ".join(fruits)) # apple | banana | cherry