เมธอด str.split() ใช้แยกสตริงเป็นลิสต์ของสตริงย่อย (Substrings) ตาม Delimiter ที่กำหนด เป็นหนึ่งในเมธอดที่ใช้บ่อยที่สุดในการประมวลผลข้อความ
ไวยากรณ์
str.split(sep=None, maxsplit=-1)
sep: Delimiter (ค่าเริ่มต้น = Whitespace ใดๆ: space, tab, newline)maxsplit: จำนวนครั้งสูงสุดที่แยก (-1 = ไม่จำกัด)
ตัวอย่างพื้นฐาน
1. แยกด้วย Whitespace (Default)
text = "Apple Banana Grapes Apple" # หลาย Space
print(text.split())
# ['Apple', 'Banana', 'Grapes', 'Apple']
# แยกด้วย Space เดียว (ไม่รวม Multiple Spaces)
print(text.split(' '))
# ['Apple', '', 'Banana', '', '', 'Grapes', '', '', '', 'Apple']
2. แยกด้วย Delimiter เฉพาะ
csv_line = "John,Doe,30,Engineer,New York"
print(csv_line.split(','))
# ['John', 'Doe', '30', 'Engineer', 'New York']
date = "2024-12-31"
print(date.split('-'))
# ['2024', '12', '31']
3. จำกัดจำนวนครั้งที่แยก (maxsplit)
text = "a,b,c,d,e"
print(text.split(',', 1)) # ['a', 'b,c,d,e'] - แยก 1 ครั้ง
print(text.split(',', 2)) # ['a', 'b', 'c,d,e'] - แยก 2 ครั้ง
print(text.split(',', -1)) # ['a', 'b', 'c', 'd', 'e'] - ไม่จำกัด (Default)
เมธอดที่เกี่ยวข้อง
rsplit() - แยกจากขวาไปซ้าย
path = "/home/user/documents/file.txt"
print(path.rsplit('/', 1)) # ['/home/user/documents', 'file.txt']
print(path.rsplit('/', 2)) # ['/home/user', 'documents', 'file.txt']
splitlines() - แยกตาม Newline
multiline = "Line 1\nLine 2\r\nLine 3\rLine 4" print(multiline.splitlines()) # ['Line 1', 'Line 2', 'Line 3', 'Line 4'] # keepends=True: เก็บ Newline ไว้ print(multiline.splitlines(keepends=True)) # ['Line 1\n', 'Line 2\r\n', 'Line 3\r', 'Line 4']
partition() / rpartition() - แยก 3 ส่วน
email = "user@example.com"
print(email.partition('@'))
# ('user', '@', 'example.com')
# เหมาะสำหรับแยก Key-Value
config = "debug=true"
key, sep, value = config.partition('=')
print(key, value) # debug true
Regular Expression Split: re.split()
สำหรับ Delimiter ที่ซับซ้อน (หลาย Pattern)
import re # แยกด้วย Comma, Semicolon, หรือ Whitespace text = "apple, banana; orange grape" print(re.split(r'[,;\s]+', text)) # ['apple', 'banana', 'orange', 'grape'] # แยกแต่เก็บ Delimiter ไว้ (ใช้ Capture Group) print(re.split(r'([,;])', "a,b;c")) # ['a', ',', 'b', ';', 'c']
การประยุกต์ใช้งานจริง
1. Parse CSV Line (Simple)
def parse_csv_line(line):
"""Simple CSV parser (ไม่จัดการ Quoted Fields)"""
return [field.strip() for field in line.split(',')]
print(parse_csv_line(" John , Doe , 30 "))
# ['John', 'Doe', '30']
2. Parse Query String
query = "name=John&age=30&city=New+York"
params = {}
for pair in query.split('&'):
if '=' in pair:
k, v = pair.split('=', 1) # maxsplit=1 สำคัญ!
params[k] = v.replace('+', ' ')
print(params) # {'name': 'John', 'age': '30', 'city': 'New York'}
3. Tokenization สำหรับ NLP
text = "Hello, world! How are you?" # Simple word tokenization words = re.findall(r'\b\w+\b', text.lower()) print(words) # ['hello', 'world', 'how', 'are', 'you']
Performance Tips
split()(ไม่มี Argument) เร็วกว่าsplit(' ')เพราะ Optimized ใน C- ใช้
maxsplitเมื่อต้องการแค่บางส่วน (เร็วกว่า) - สำหรับ CSV จริง ใช้
csvmodule หรือpandas.read_csv
สรุป
| เมธอด | ใช้เมื่อ |
|---|---|
split() | แยกด้วย Whitespace ทั่วไป (Default) |
split(sep) | แยกด้วย Delimiter เฉพาะ |
split(sep, maxsplit) | จำกัดจำนวนครั้งที่แยก |
rsplit() | แยกจากขวา (เหมาะสำหรับ Path, Extension) |
splitlines() | แยกบรรทัด (Cross-platform Newlines) |
partition() | แยก 3 ส่วน (Key/Value, Head/Tail) |
re.split() | Delimiter หลาย Pattern หรือ Complex |