Python分区和拆分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21568321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python partition and split
提问by Marcos Guimaraes
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:
我想使用 split 和 partition 将一个字符串拆分为两个单词,例如“word1 word2”,并分别打印(使用 for)这些单词,例如:
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']
采纳答案by Floris
A command like name.split()returns a list. You might consider iterating over that list:
类似的命令name.split()返回一个列表。您可能会考虑迭代该列表:
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:
将执行命令print name.split(" ")两次(一次为 value i=1,一次为i=2)。两次它会打印出整个结果:
['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
类似的事情发生在partition- 除了它也返回您拆分的元素之外。所以在这种情况下你可能想要做
print name.partition(" ")[0:3:2]
# or
print name.partition(" ")[0::2]
to return elements 0and 2. Alternatively, you can do
返回元素0和2。或者,你可以做
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
在循环中连续两次打印元素 0 和 2。请注意,后一种代码效率更低,因为它计算了两次分区。如果你在乎,你可以写
train = (0,2,)
part = name.partition(" ")
for i in train:
print part[i]
回答by thefourtheye
str.partitionreturns 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
str.partition返回一个包含三个元素的元组。分区字符串之前的字符串、分区字符串本身和字符串的其余部分。所以,它必须像这样使用
first, middle, rest = name.partition(" ")
print first, rest
To use the str.split, you can simply print the splitted strings like this
要使用str.split,您可以像这样简单地打印拆分的字符串
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 Nonein splitor specifying no parameters, this is what happens
注意:使用Noneinsplit或不指定参数,会发生这种情况
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 [].
如果未指定 sep 或为 None ,则应用不同的拆分算法:将连续空格的运行视为单个分隔符,如果字符串有前导或尾随空格,则结果将在开头或结尾不包含空字符串。因此,拆分空字符串或仅由空格组成的字符串与 None 分隔符将返回 []。
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.joinmethod like this
或者你可以使用这样的str.join方法
print "Partition:"
first, middle, rest = name.partition(" ")
print "\n".join((first, rest))
print "Split:"
print "\n".join(name.split())
回答by Preeti Duhan
The partition()method splits the string at the first occurrenceof the separator and returns a tuple containing 3 elements :
该partition()方法在分隔符第一次出现时拆分字符串,并返回一个包含 3 个元素的元组:
- the part before separator
- the separator
- 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.')
While with split():
使用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 ', 'a good person and Preeti', '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.
简单地说, split 将在给定参数的任何出现处拆分字符串,而 partition 只会在给定参数第一次出现时拆分字符串,并返回一个以给定参数作为中间值的三元组。
You might also look at the rpartition()method.
你也可以看看rpartition()方法。

