Strings
String คือลำดับของ Unicode characters
หัวข้อที่มีชื่อว่า “String คือลำดับของ Unicode characters”Python 3 strings (str) เป็นลำดับ Unicode code points ที่เปลี่ยนแปลงไม่ได้
Single quotes และ double quotes ใช้แทนกันได้ — เลือกแบบหนึ่งแล้วใช้สม่ำเสมอ
Triple quotes (""" หรือ ''') อนุญาตให้สร้าง string หลายบรรทัด
a = "Hello"b = 'World'c = """This spansmultiple lines."""String methods ที่ใช้บ่อย
หัวข้อที่มีชื่อว่า “String methods ที่ใช้บ่อย”String มี methods มากมาย เหล่านี้คือที่คุณจะใช้เป็นประจำ:
s = " Hello, Python! "print(s.strip()) # "Hello, Python!"print(s.upper()) # " HELLO, PYTHON! "print(s.lower()) # " hello, python! "print(s.replace("Python", "World")) # " Hello, World! "print(s.startswith(" H")) # Trueprint(s.endswith("! ")) # Trueprint(len(s)) # 18Methods คืน string ใหม่ — ไม่เคยแก้ไข string ต้นฉบับ
Slicing
หัวข้อที่มีชื่อว่า “Slicing”String รองรับไวยากรณ์ slicing แบบเดียวกับ list: s[start:stop:step]
Index ติดลบนับจากท้าย
s = "Hello, Python!"print(s[0:5]) # Helloprint(s[7:]) # Python!print(s[-7:]) # Python!print(s[::-1]) # !nohtyP ,olleH (กลับด้าน)print(s[::2]) # Hlo,Pto!f-strings (formatted string literals)
หัวข้อที่มีชื่อว่า “f-strings (formatted string literals)”f-strings เปิดตัวใน Python 3.6 เป็นวิธีมาตรฐานในการฝังนิพจน์ใน string
ใส่ prefix f ก่อน string แล้ววางนิพจน์ Python ใดก็ได้ไว้ใน {}
name = "Alice"age = 30pi = 3.14159
print(f"Name: {name}, Age: {age}")print(f"Pi to 2dp: {pi:.2f}")print(f"2 + 2 = {2 + 2}")print(f"Upper: {name.upper()}")Format specifiers หลัง : ควบคุมการจัดวาง, ความแม่นยำ, และชนิด — mini-language เดียวกับที่ใช้ใน str.format()
join() และ split()
หัวข้อที่มีชื่อว่า “join() และ split()”str.split(sep) แบ่ง string เป็น list
sep.join(iterable) รวม list ของ string เป็น string เดียว
ทั้งสองเป็นการกลับกันของกัน
csv = "one,two,three,four"parts = csv.split(",") # ['one', 'two', 'three', 'four']rejoined = " | ".join(parts) # 'one | two | three | four'print(parts)print(rejoined)ใช้ string method join เสมอ (", ".join(items)) ไม่ควร concatenate ใน loop — การ concatenate ใน loop สร้าง string กลางที่ไม่จำเป็น O(n²) ชิ้น
Demo ที่รันได้จริง
หัวข้อที่มีชื่อว่า “Demo ที่รันได้จริง”s = "Hello, Python!"print(s.upper())print(s.lower())print(s.replace("Python", "World"))print(s.startswith("Hello"))print(len(s))
print(s[0:5])print(s[-7:])print(s[::2])
name = "Alice"age = 30pi = 3.14159print(f"Name: {name}, Age: {age}")print(f"Pi to 2dp: {pi:.2f}")
words = ["one", "two", "three"]joined = ", ".join(words)print(joined)parts = "a:b:c:d".split(":")print(parts)
try: s[0] = "h"except TypeError as e: print(f"TypeError: {e}")Loading Python runtime (first run only)…