ข้ามไปยังเนื้อหา

Strings

Python 3 strings (str) เป็นลำดับ Unicode code points ที่เปลี่ยนแปลงไม่ได้ Single quotes และ double quotes ใช้แทนกันได้ — เลือกแบบหนึ่งแล้วใช้สม่ำเสมอ Triple quotes (""" หรือ ''') อนุญาตให้สร้าง string หลายบรรทัด

a = "Hello"
b = 'World'
c = """This spans
multiple lines."""

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")) # True
print(s.endswith("! ")) # True
print(len(s)) # 18

Methods คืน string ใหม่ — ไม่เคยแก้ไข string ต้นฉบับ

String รองรับไวยากรณ์ slicing แบบเดียวกับ list: s[start:stop:step] Index ติดลบนับจากท้าย

s = "Hello, Python!"
print(s[0:5]) # Hello
print(s[7:]) # Python!
print(s[-7:]) # Python!
print(s[::-1]) # !nohtyP ,olleH (กลับด้าน)
print(s[::2]) # Hlo,Pto!

f-strings เปิดตัวใน Python 3.6 เป็นวิธีมาตรฐานในการฝังนิพจน์ใน string ใส่ prefix f ก่อน string แล้ววางนิพจน์ Python ใดก็ได้ไว้ใน {}

name = "Alice"
age = 30
pi = 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()

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²) ชิ้น

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 = 30
pi = 3.14159
print(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}")
`"Hello, World!"[7:]` คืนค่าอะไร?
วิธีมาตรฐานในการ concatenate list ของ string คืออะไร?
prefix `f` ใน `f"Hello {name}"` ทำอะไร?
ทำไม string ใน Python จึงถูกเรียกว่า immutable?