gpt4 book ai didi

Python分区和拆分

转载 作者:太空狗 更新时间:2023-10-29 18:13:37 25 4
gpt4 key购买 nike

我想使用 split 和 partition 将一个字符串拆分为两个单词,例如“word1 word2”,然后分别打印(使用 for)这些单词,例如:

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

最佳答案

str.partition返回三个元素的元组。分区字符串之前的字符串、分区字符串本身和字符串的其余部分。所以,它必须这样使用

first, middle, rest = name.partition(" ")
print first, rest

使用str.split , 你可以像这样简单地打印拆分后的字符串

print name.split(" ")

但是,当你这样调用它时,如果字符串有一个以上的空格字符,你将得到两个以上的元素。例如

name = "word1 word2 word3"
print name.split(" ") # ['word1', 'word2', 'word3']

如果只想拆分一次,可以指定拆分次数作为第二个参数,像这样

name = "word1 word2 word3"
print name.split(" ", 1) # ['word1', 'word2 word3']

但是,如果您尝试根据空白字符进行拆分,则不必传递 ""。你可以简单地做

name = "word1 word2 word3"
print name.split() # ['word1', 'word2', 'word3']

如果要限制拆分次数,

name = "word1 word2 word3"
print name.split(None, 1) # ['word1', 'word2 word3']

注意split中使用None或者不指定任何参数,会发生这种情况

引自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 [].

所以,你可以像这样改变你的程序

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

或者您可以使用 str.join这样的方法

print "Partition:"
first, middle, rest = name.partition(" ")
print "\n".join((first, rest))

print "Split:"
print "\n".join(name.split())

关于Python分区和拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com