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

วิธีดึง Substring จาก String ใน Python

ใน Python String เป็น Ordered Sequence ของ Characters Sequence Types ทั้งหมดรองรับ Slicing ใช้ Slice Operator : ดึง Substring จาก String หลัก

ตัวอย่าง

>>> string="Hello How are you?"
>>> string[6:9]
'How'

Slice Operator ต้องการ 2 Operands: Operand แรก = Index ตัวแรกของ Substring ที่ต้องการ Operand ที่สอง = Index ตัวสุดท้าย + 1 (ไม่รวม) ตัวอย่าง Index 6-8 จะได้ Substring (Index เริ่มจาก 0)