溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python中split()函數(shù)的使用方法

發(fā)布時(shí)間:2021-03-04 13:11:01 來源:億速云 閱讀:19688 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)Python中split()函數(shù)的使用方法,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

在Python中,split() 方法可以實(shí)現(xiàn)將一個(gè)字符串按照指定的分隔符切分成多個(gè)子串,這些子串會(huì)被保存到列表中(不包含分隔符),作為方法的返回值反饋回來。

split函數(shù)用法

split(sep=None, maxsplit=-1)

參數(shù)

sep – 分隔符,默認(rèn)為所有的空字符,包括空格、換行(\n)、制表符(\t)等。

maxsplit – 分割次數(shù)。默認(rèn)為 -1, 即分隔所有。

實(shí)例:

// 例子

String = 'Hello world! Nice to meet you'

String.split()
['Hello', 'world!', 'Nice', 'to', 'meet', 'you']

String.split(' ', 3)
['Hello', 'world!', 'Nice', 'to meet you']

String1, String2 = String.split(' ', 1) 
// 也可以將字符串分割后返回給對(duì)應(yīng)的n個(gè)目標(biāo),但是要注意字符串開頭是否存在分隔符,若存在會(huì)分割出一個(gè)空字符串
String1 = 'Hello'
String2 = 'world! Nice to meet you'

String.split('!')
// 選擇其他分隔符
['Hello world', ' Nice to meet you']

split函數(shù)實(shí)現(xiàn)

    def split(self, *args, **kwargs): # real signature unknown
        """
        Return a list of the words in the string, using sep as the delimiter string.
        
          sep
            The delimiter according which to split the string.
            None (the default value) means split according to any whitespace,
            and discard empty strings from the result.
          maxsplit
            Maximum number of splits to do.
            -1 (the default value) means no limit.
        """
        pass

上圖為Pycharm文檔

def my_split(string, sep, maxsplit):
    ret = []
    len_sep = len(sep)
    if maxsplit == -1:
        maxsplit = len(string) + 2
    for _ in range(maxsplit):
        index = string.find(sep)
        if index == -1:
            ret.append(string)
            return ret
        else:
            ret.append(string[:index])
            string = string[index + len_sep:]
    ret.append(string)
    return ret


if __name__ == "__main__":
    print(my_split("abcded", "cd", -1))
    print(my_split('Hello World! Nice to meet you', ' ', 3))

關(guān)于“Python中split()函數(shù)的使用方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI