Splitting strings looks trivial until an empty string or an extra space breaks your parser.
1. split() vs split(' ') are not the same
"a b".split() # ['a', 'b']
"a b".split(' ') # ['a', '', 'b']
With no argument, split() splits on any whitespace run and drops empty strings. With an explicit separator, every occurrence counts, so consecutive separators produce empty strings.
2. Empty input behaves differently too
"".split() # []
"".split(',') # [''] <- a list with one item, not an empty list
If you read CSV-like fields, this is where an empty field becomes a phantom row.
3. Limit splits with maxsplit
"key=value=with=equals".split('=', 1)
# ['key', 'value=with=equals']
4. Split from the right with rsplit
"scene.final.blend".rsplit('.', 1)
# ['scene.final', 'blend']
Useful for file extensions. For real paths, prefer os.path.splitext or pathlib.Path.suffix.
5. Use partition when you expect exactly one separator
host, _, port = "localhost:8080".partition(':')
# host='localhost', port='8080'
It always returns three items, even if the separator is missing (('localhost', '', '')), so unpacking never raises ValueError.
6. Use splitlines() instead of split('\n')
"a\r\nb".split('\n') # ['a\r', 'b']
"a\r\nb".splitlines() # ['a', 'b']
It handles \r\n, \r, and other line endings, so it's safer for files created on Windows.
7. Multiple delimiters? Use re.split
import re
re.split(r'[,;\s]+', "a, b;c d")
# ['a', 'b', 'c', 'd']
Rule of thumb
-
split()for whitespace -
split(sep, n)orpartition()for structured strings -
splitlines()for text files -
re.split()when there's more than one kind of separator
Top comments (1)
Việc xử lý các chuỗi có khoảng trắng thừa hoặc ký tự xuống dòng bằng split() mà không truyền tham số đúng là một cái bẫy khá phổ biến. Mình từng mất khá nhiều thời gian debug khi parser bị lỗi chỉ vì một dòng trống nằm xen kẽ trong file cấu hình. Một mẹo nhỏ là nếu bạn muốn loại bỏ hoàn toàn các khoảng trắng dư thừa ở đầu và cuối mỗi phần tử sau khi split, hãy kết hợp với list comprehension và strip(). Việc dùng split() mặc định với tham số None thường an toàn hơn cho các trường hợp phân tách dựa trên whitespace, nhưng nếu cần độ chính xác tuyệt đối với các ký tự đặc biệt, dùng regex module là lựa chọn ít gây đau đầu nhất.