Python partition and split

Marcos Guimaraes picture Marcos Guimaraes · Feb 5, 2014 · Viewed 66.6k times · Source

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']

Answer

thefourtheye picture thefourtheye · Feb 5, 2014

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