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

ตรวจสอบว่า substring อยู่ใน string หรือไม่ใน Python

ตรวจสอบว่าสตริงย่อย (substring) เป็นส่วนหนึ่งของสตริงใหญ่หรือไม่

ใช้ find()

find() คืน index แรกที่เจอ หรือ -1 ถ้าไม่เจอ

ตัวอย่าง

Astring = "In cloud 9"
Asub_str = "cloud"
print("Given string: ", Astring)
print("Given substring: ", Asub_str)
if Astring.find(Asub_str) == -1:
    print("Substring is not a part of the string")
else:
    print("Substring is part of the string")

Asub_str = "19"
print("Given substring: ", Asub_str)
if Astring.find(Asub_str) == -1:
    print("Substring is not a part of the string")
else:
    print("Substring is part of the string")

ผลลัพธ์

Given string: In cloud 9
Given substring: cloud
Substring is part of the string
Given substring: 19
Substring is not a part of the string

ใช้ count()

count() นับจำนวนครั้งที่พบ ถ้า > 0 แปลว่ามี

ตัวอย่าง

Astring = "In cloud 9"
Asub_str = "cloud"
print("Given string: ", Astring)
print("Given substring: ", Asub_str)
if Astring.count(Asub_str) > 0:
    print("Substring is part of the string")
else:
    print("Substring is not a part of the string")

Asub_str = "19"
print("Given substring: ", Asub_str)
if Astring.count(Asub_str) > 0:
    print("Substring is part of the string")
else:
    print("Substring is not a part of the string")

ผลลัพธ์

Given string: In cloud 9
Given substring: cloud
Substring is part of the string
Given substring: 19
Substring is not a part of the string