Python分区和拆分 [英] Python partition and split
问题描述
我想使用 split 和 partition 将一个包含两个单词的字符串拆分,例如word1 word2",然后分别打印(使用 for)这些单词,例如:
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
这是我的代码:
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(" ")
这是正在发生的:
Separation with partition:
('word1', ' ', 'word2')
('word1', ' ', 'word2')
Separation with split:
['word1', 'word2']
['word1', 'word2']
推荐答案
像 name.split()
这样的命令返回一个列表.您可能会考虑迭代该列表:
A command like name.split()
returns a list. You might consider iterating over that list:
for i in name.split(" "):
print i
因为你写的东西,即
for i in train:
print name.split(" ")
将执行命令 print name.split(" ")
两次(一次用于值 i=1
,一次用于 i=2
代码>).两次它会打印出整个结果:
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']
类似的事情发生在 partition
- 除了它返回你分割的元素.所以在这种情况下你可能想要做
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]
返回元素 0
和 2
.或者,你可以这样做
to return elements 0
and 2
. Alternatively, you can do
train = (0, 2,)
for i in train:
print name.partition(" ")[i]
在循环中连续两次打印元素 0 和 2.请注意,后一种代码效率更低,因为它计算了两次分区.如果你在乎,你可以写
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]
这篇关于Python分区和拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!