Python partition and split

前端 未结 3 1521
一整个雨季
一整个雨季 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:06

    A command like name.split() returns a list. You might consider iterating over that list:

    for i in name.split(" "):
      print i
    

    Because the thing you wrote, namely

    for i in train:
      print name.split(" ")
    

    will execute the command print name.split(" ") twice (once for value i=1, and once more for i=2). And twice it will print out the entire result:

    ['word1', 'word2']
    ['word1', 'word2']
    

    A similar thing happens with partition - except it returns the element that you split as well. So in that case you might want to do

    print name.partition(" ")[0:3:2]
    # or
    print name.partition(" ")[0::2]
    

    to return elements 0 and 2. Alternatively, you can do

    train = (0, 2,)
    for i in train:
      print name.partition(" ")[i]
    

    To print element 0 and 2 in two consecutive passes through the loop. Note that this latter code is more inefficient as it computes the partition twice. If you cared, you could write

    train = (0,2,)
    part = name.partition(" ")
    for i in train:
      print part[i]
    
    0 讨论(0)
  • 2020-12-31 07:11

    str.partition returns a tuple of three elements. String before the partitioning string, the partitioning string itself and the rest of the string. So, it has to be used like this

    first, middle, rest = name.partition(" ")
    print first, rest
    

    To use the str.split, you can simply print the splitted strings like this

    print name.split(" ")
    

    But, when you call it like this, if the string has more than one space characters, you will get more than two elements. For example

    name = "word1 word2 word3"
    print name.split(" ")          # ['word1', 'word2', 'word3']
    

    If you want to split only once, you can specify the number times to split as the second parameter, like this

    name = "word1 word2 word3"
    print name.split(" ", 1)       # ['word1', 'word2 word3']
    

    But, if you are trying to split based on the whitespace characters, you don't have to pass " ". You can simply do

    name = "word1 word2 word3"
    print name.split()            # ['word1', 'word2', 'word3']
    

    If you want to limit the number of splits,

    name = "word1 word2 word3"
    print name.split(None, 1)     # ['word1', 'word2 word3']
    

    Note: Using None in split or specifying no parameters, this is what happens

    Quoting from the split documentation

    If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

    So, you can change your program like this

    print "Partition:"
    first, middle, rest = name.partition(" ")
    for current_string in (first, rest):
        print current_string
    
    print "Split:"
    for current_string in name.split(" "):
        print current_string
    

    Or you can use str.join method like this

    print "Partition:"
    first, middle, rest = name.partition(" ")
    print "\n".join((first, rest))
    
    print "Split:"
    print "\n".join(name.split())
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题