Python partition and split

最后都变了- 提交于 2020-01-10 18:21:31

问题


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
word2

Split:
word1
word2

This is my code:

print("Hello World")
name = raw_input("Type your name: ")

train = 1,2
train1 = 1,2
print("Separation with partition: ")
for i in train1:
    print name.partition(" ")

print("Separation with split: ")
for i in train1:
    print name.split(" ")

This is happening:

Separation with partition: 
('word1', ' ', 'word2')
('word1', ' ', 'word2')

Separation with split: 
['word1', 'word2']
['word1', 'word2']

回答1:


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]



回答2:


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())



回答3:


The partition() method splits the string at the first occurrence of the separator and returns a tuple containing the part the before separator, separator and 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.')

And in 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 ', 'is ', 'a good person and Preeti','is','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.



来源:https://stackoverflow.com/questions/21568321/python-partition-and-split

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!