String trong Python là ordered sequence of characters. Tất cả sequence type hỗ trợ slicing. Dùng slice operator : để lấy substring.
Ví dụ
>>> string = "Hello How are you?" >>> string[6:9] 'How'
Slice operator cần 2 operand:
- Operand 1: index ký tự đầu substring (bắt đầu từ 0)
- Operand 2: index cuối + 1 (substring chứa ký tự đến index này - 1)
Ví dụ trên: index 6-8 → 'How'.
Các dạng slicing hữu ích
s = "Hello World" s[6:] # "World" (từ index 6 đến cuối) s[:5] # "Hello" (từ đầu đến index 4) s[-5:] # "World" (5 ký tự cuối) s[::2] # "HloWrd" (mỗi 2 ký tự) s[::-1] # "dlroW olleH" (reverse)