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

Python – หาตำแหน่งทั้งหมดของ Substring ในสตริง

บทความนี้สาธิตวิธีหาตำแหน่ง (Index) ทุกตำแหน่งที่ Substring ปรากฏในสตริงหลัก โดยใช้ startswith() ร่วมกับ List Comprehension

โค้ดตัวอย่าง

my_string = "Python learn code test fun amazing object oriented"
sub_string = "object"

print(f"สตริงหลัก: {my_string}")
print(f"Substring ที่หา: '{sub_string}'")

# หาตำแหน่งทั้งหมดที่ sub_string เริ่มต้น
# ใช้ startswith(sub_string, index) ตรวจสอบทุกตำแหน่ง
my_result = [index for index in range(len(my_string)) 
             if my_string.startswith(sub_string, index)]

print(f"\nตำแหน่งที่เจอ: {my_result}")

ผลลัพธ์

สตริงหลัก: Python learn code test fun amazing object oriented
Substring ที่หา: 'object'
ตำแหน่งที่เจอ: [35]

อธิบายการทำงาน

  • range(len(my_string)) สร้างลำดับตัวเลข 0 ถึง ความยาวสตริง-1
  • my_string.startswith(sub_string, index) ตรวจสอบว่าตั้งแต่ตำแหน่ง index เริ่มต้นด้วย sub_string หรือไม่
  • List Comprehension เก็บเฉพาะ Index ที่เงื่อนไขเป็น True

ตัวอย่างหลาย Match

text = "ababababa"
pattern = "aba"
positions = [i for i in range(len(text)) if text.startswith(pattern, i)]
print(positions)  # [0, 2, 4, 6]

วิธีทางเลือก: ใช้ find() ในลูป

def find_all_occurrences(text, pattern):
    """หาตำแหน่งทั้งหมดด้วย find() - เร็วกว่าสำหรับสตริงยาว"""
    positions = []
    start = 0
    while True:
        pos = text.find(pattern, start)
        if pos == -1:
            break
        positions.append(pos)
        start = pos + 1  # หาต่อจากตัวถัดไป (allow overlapping)
    return positions

print(find_all_occurrences("ababababa", "aba"))  # [0, 2, 4, 6]

การประยุกต์ใช้

  • การค้นหาคำในเอกสาร (Text Search)
  • การวิเคราะห์ DNA Sequence
  • การตรวจสอบรูปแบบใน Log files
  • Feature Extraction ใน NLP