Strings

ประเภทข้อมูลใน Python

Jason Myers

Instructor

การสร้าง formatted string

  • f-strings (formatted string literals) - f""
cookie_name = "Anzac"
cookie_price = "$1.99"

print(f"Each { cookie_name } cookie costs { cookie_price }.")
"Each Anzac cookie costs $1.99."
ประเภทข้อมูลใน Python

การเชื่อม string

  • "".join() ใช้ string ที่เรียกใช้เพื่อเชื่อม iterable เข้าด้วยกัน
child_ages = ["3", "4", "7", "8"]

print(", ".join(child_ages))
"3, 4, 7, 8"
print(f"The children are ages {','.join(child_ages[0:3])}, and {child_ages[-1]}.")
"The children are ages 3, 4, 7, and 8."
ประเภทข้อมูลใน Python

การจับคู่ส่วนหนึ่งของ string

  • เมธอด .startswith() และ .endswith() ใช้ตรวจสอบว่า string ขึ้นต้นหรือลงท้ายด้วยอักขระหรือ string ที่กำหนดหรือไม่
boy_names = ["Mohamed", "Youssef", "Ahmed"]
print([name for name in boy_names if name.startswith('A')])
["Ahmed"]
  • โปรดระวัง เมธอดเหล่านี้และฟังก์ชัน string ส่วนใหญ่จะคำนึงถึงตัวพิมพ์เล็ก-ใหญ่
ประเภทข้อมูลใน Python

การค้นหาค่าใน string

  • ตัวดำเนินการ in ใช้ค้นหาค่าใน iterable เช่น string
"long" in "Life is a long lesson in humility."
True
"life" in "Life is a long lesson in humility."
False
ประเภทข้อมูลใน Python

การทำให้ไม่คำนึงถึงตัวพิมพ์เล็ก-ใหญ่

  • เมธอด .lower() คืนค่า string ที่เป็นตัวพิมพ์เล็กทั้งหมด
"life" in "Life is a long lesson in humility.".lower()
True
ประเภทข้อมูลใน Python

มาฝึกกันเถอะ!

ประเภทข้อมูลใน Python

Preparing Video For Download...