Python partition and split
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())
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]