SkillByAIOpen interactive version →

Lesson 17 / 49

Slicing, Split & Join

Slice strings like sequences, split text into lists and join lists back into text.

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