user3260052 user3260052 - 1 month ago 15
Python Question

Python partition and split

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

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]

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