Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การพิมพ์ตัวอักษรที่ 3-5 ของสตริงใน Python (String Slicing)

Python ใช้ Slice Operator [:] ดึง Substring: string[start:end] โดย start = index เริ่มต้น (รวม, 0-based), end = index ถัดจากตัวสุดท้าย (ไม่รวม)

ตัวอย่าง: ตัวอักษรที่ 3 ถึง 5 (1-based) = Index 2 ถึง 4

>> string = 'abcdefghij'
>>> string[2:5]
'cde'

การนับ Index

Slice Patterns พิเศษ

Syntaxหมายถึงตัวอย่าง 'abcdef'
s[2:5]Index 2,3,4'cde'
s[:5]Index 0-4 (5 ตัวแรก)'abcde'
s[2:]Index 2 ถึงสุด'cdef'
s[-3:]3 ตัวท้าย'def'
s[:-3]ทั้งหมดยกเว้น 3 ตัวท้าย'abc'
s[::2]ทุก 2 ตัว (Step=2)'ace'
s[::-1]กลับสตริง (Reverse)'fedcba'