Python partition and split

前端 未结 3 1563
一整个雨季
一整个雨季 2020-12-31 06:48

I want to split a string with two words like \"word1 word2\" using split and partition and print (using a for) the words separately like:

Partition:
word1
wo         


        
3条回答
  •  旧巷少年郎
    2020-12-31 07:18

    The partition() method splits the string at the first occurrence of the separator and returns a tuple containing 3 elements :

    • the part before separator
    • the separator
    • the part after the separator
    string = "Deepak is a good person and Preeti is not a good person."  # 'is' separator is found at first occurence
    print(string.partition('is ')) 
    

    Output:

    ('Deepak ', 'is ', 'a good person and Preeti is not a good person.')
    

    While with split() :

    string = "Deepak is a good person and Preeti is not a good person."  # 'is' separator is found at every occurence 
    print(string.partition('is ')) 
    

    Output:

    ['Deepak ', 'a good person and Preeti', 'not a good person.']
    

    Simply put, split will split the string at any occurrence of the given argument, while partition will only split the string at the first occurrence of the given argument and will return a 3-tuple with the given argument as the middle value.

    You might also look at the rpartition() method.

提交回复
热议问题