String slicing is a powerful technique to extract parts of strings using the syntax:
string[start:stop:step]
Negative indices and steps can be used for reverse slicing and other effects.
text = "Hello, World!"
# 1. Slice from index 0 to 4 (first 5 chars)
print(text[0:5]) # Output: Hello
# 2. Slice from index 7 to end
print(text[7:]) # Output: World!
# 3. Slice from start to index 4
print(text[:5]) # Output: Hello
# 4. Slice entire string
print(text[:]) # Output: Hello, World!
# 5. Step slicing - every 2nd character
print(text[::2]) # Output: Hlo ol!
# Using negative indices to slice from the end
# 6. Last character
print(text[-1]) # Output: !
# 7. Last 6 characters
print(text[-6:]) # Output: World!
# 8. Slice excluding last character
print(text[:-1]) # Output: Hello, World
# 9. Slice from -6 to -1 (excluding last char)
print(text[-6:-1]) # Output: World
# 10. Using negative step to reverse string
print(text[::-1]) # Output: !dlroW ,olleH
# 11. Every 3rd character
print(text[::3]) # Output: Hl r!
# 12. Reverse every 2nd character
print(text[::-2]) # Output: !lo rH
# 13. Slice subset and reverse
print(text[7:12][::-1]) # Output: dlroW
# 14. Negative step with start and stop
print(text[12:7:-1]) # Output: dlroW
# 15. Slice from middle to start, stepping backwards by 2
print(text[10:0:-2]) # Output: l rH
# 16. Start index > stop index without negative step returns empty string
print(text[5:2]) # Output: ''
# 17. Out-of-range indices are handled gracefully
print(text[0:100]) # Output: Hello, World!
# 18. Empty slice when step is zero (raises error)
# print(text[::0]) # Uncommenting raises ValueError
# 19. Single character slice
print(text[4:5]) # Output: o
# 20. Slice with step larger than string length
print(text[::50]) # Output: H