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

Python - ตรวจสอบว่าสตริงขึ้นต้นด้วย Substring ที่กำหนดด้วย Regex

ตรวจสอบว่าสตริงเริ่มต้นด้วย Substring ที่กำหนด โดยใช้ Regex ^ + substring และ re.search()

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

import re

def check_string(my_string, sub_string):
    if sub_string in my_string:
        concat_string = "^" + sub_string
        result = re.search(concat_string, my_string)
        if result:
            print("The string starts with the given substring")
        else:
            print("The string does not start with the given substring")
    else:
        print("It is not a substring")

my_string = "Python coding is fun to learn"
sub_string = "Python"
print("The string is :")
print(my_string)
print("The sub-string is :")
print(sub_string)
check_string(my_string, sub_string)

ผลลัพธ์

The string is : Python coding is fun to learn
The sub-string is : Python
The string starts with the given substring

คำอธิบาย

  • เช็คก่อนว่า substring อยู่ในสตริงหรือไม่ (Optional)
  • สร้าง pattern "^" + sub_string (^ หมายถึงต้นสตริง)
  • re.search() หา pattern นี้
  • วิธีง่ายกว่า: my_string.startswith(sub_string) ไม่ต้องใช้ Regex