Python partition and split

前端 未结 3 1562
一整个雨季
一整个雨季 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]
    

提交回复
热议问题