Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

動手設計一個 Python 字符串分割函數

自己設計一個分割函數,分隔符可以換成任意字符串,這裡先用連續的點號做例子。

s = 'xbc..w1z2x......yd3c....eeff'
print(s)

sep = '..'

def my_split(src, sep):
    a = src.find(sep)
    print(src[:a])

    b = a
    n = len(sep)
    while b <= len(src) and b != -1:
        # 跳過連續重複的分隔符
        while src[a:a + n] == sep:
            a = a + n
        b = src.find(sep, a)
        if b != -1:
            print(src[a:b])
        else:
            print(src[a:])
        a = b

print('enter my_split')
my_split(s, sep)
print('=============================')
my_split(s, '.')
print('=============================')
my_split(s, '...')
print('leave my_split')

這個手寫版本的關鍵在於內層的 while:它能吸收「......」這種連續出現的分隔符,避免切出空字符串——這一步是很多初學版本會漏掉的。注意函數內應使用傳入的 src 而非外部的 s,否則換參數調用時結果會不對。

當然,實戰中直接用內建的 str.split() 就好,它天然支持多字符分隔符並自動忽略連續分隔產生的空項:

s.split('..')      # 以 .. 分割
s.split('.')       # 以 . 分割
s.split('...')     # 以 ... 分割

手寫一遍的價值不在於替代標準庫,而在於真正搞懂索引移動與邊界判斷——這些基本功在處理協議報文、CSV 變體等格式時仍然用得上。

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved