python基礎之實現split函式

2021-10-08 08:12:47 字數 1849 閱讀 7733

思路就是先找到分割的位置,那麼就需要前面的split函式,接著分割即可

def

my_find

(source,target,start=0)

:ifnot source or

not target:

return-1

iflen

(target)

>

len(source)

:return-1

if start <

0or start >=

len(source)

:return-1

for index in

range

(start,

len(source)

-len

(target)+1

):t_index =

0while t_index <

len(target)

:if target[t_index]

== source[t_index+index]

: t_index +=

1else

:break

if t_index ==

len(target)

:return index

return-1

defmy_split

(source,sep,maxsplit=-1

):ifnot source or

not sep:

return

lst =

max_split_count = maxsplit if maxsplit >

0else

len(source)

#用於定義分幾次

split_count =

0

start_index =

0#開始的位置

index = my_find(source,sep,start = start_index)

#找到第一次的分界點

while split_count < max_split_count and index !=-1

:#用於判斷是否找完了

sep_str = source[start_index:index]

#擷取第一次的長度,就是第一次分界的長度

#加入列表

split_count +=

1#+1

start_index = index +

len(sep)

#第二次分界開始的地方

index = my_find(source,sep,start=start_index)

#從第二次分界的地方往後尋找新的分界點,以此迴圈

sep_str = source[start_index:

]#擷取最後乙個分界點後面的所有內容

#加入列表

return lst

if __name__ ==

"__main__"

:print

(my_split(

"1,3,4"

,","))

print

(my_split(

"1,,3,,4"

,",,"))

print

(my_split(

"abcadae"

,"a"))

print

(my_split(

"abcadae"

,"a"

,maxsplit=2)

)print

(my_split(

"aaaa"

,"a"

))

python基礎之實現float函式

本題只將字串型別的數字轉換為float資料 實現思路 重點是找到小數點的位置,然後除去相應的值,就能獲得對應的小數 實現float 只將字串轉換為float型別的資料 如 34.22 轉換為34.22 str int dict defmy float string string list strin...

python基礎篇之實用庫

python 的實用離不開其強大的庫或框架的支援,像正規表示式,檔案模組,命令列模組,django 框架,sk learning 工具箱等.這些都讓 python 能夠非常方便的處理不同領域的問題。初學 python,對 python 的文書處理能力有很深的印象,除了 str 物件自帶的一些方法外,...

Python之實現聊天室

from socket import import threading s1 socket af inet,sock dgram localhost 192.168.2.216 8077 otherhost 192.168.2.216 8088 s1.bind localhost defmain p...