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

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

เมื่อต้องการหาตำแหน่งเริ่มต้นทั้งหมดของ substring ในสตริง สามารถใช้ list comprehension และ startswith() ได้

ตัวอย่าง

my_string = "Is python fun to learn?"
print("The list is :")
print(my_string)
substring = "pyt"
print("The substring is :")
print(substring)
my_result = [i for i in range(len(my_string)) if my_string.startswith(substring, i)]
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : Is python fun to learn?
The substring is : pyt
The result is : [3]

คำอธิบาย

  • กำหนดสตริงหลักและ substring ที่ต้องการค้นหา

  • ใช้ list comprehension วนดัชนี i ทุกตำแหน่งในสตริง

  • ใช้ my_string.startswith(substring, i) ตรวจสอบว่าตั้งแต่ตำแหน่ง i เริ่มด้วย substring หรือไม่

  • เก็บดัชนี i ที่ตรงเงื่อนไข แสดงผลลัพธ์