python 中字符串中每隔一个逗号后的字符串拆分
我有一个字符串,其中包含用逗号分隔的每个单词。我想在 python 中用每个其他逗号分割字符串。我该怎么做?
例如,"xyz,abc,jkl,pqr"
应该将 "xyzabc"
作为一个字符串,将 "jklpqr"
作为另一个字符串
I have string which contains every word separated by comma. I want to split the string by every other comma in python. How should I do this?
eg, "xyz,abc,jkl,pqr"
should give "xyzabc"
as one string and "jklpqr"
as another string
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在每个逗号上拆分,然后重新连接对可能更容易,
这是您想要的吗?
It's probably easier to split on every comma, and then rejoin pairs
Is that what you wanted?
分开,又重新结合。
因此,拆分:
并重新加入:
这是可行的,因为
([z]*2)
是两个元素的列表,这两个元素都是相同的迭代器z
。因此,zip 从z
中获取第一个元素,然后是第二个元素来创建每个元组。这也可以用作单行代码,因为在
[foo]*n
中foo
仅计算一次,无论它是变量还是更复杂的表达式:我已经还删除了一对括号,因为一元
*
的优先级低于二进制*
。感谢 @pillmuncher 指出,可以使用 izip_longest 进行扩展,以处理具有奇数个元素的列表:(
请参阅:http://docs.python.org/library/itertools.html#itertools.izip_longest )
Split, and rejoin.
So, to split:
And to rejoin:
This works because
([z]*2)
is a list of two elements, both of which are the same iteratorz
. Thus, zip takes the first, then second element fromz
to create each tuple.This also works as a oneliner, because in
[foo]*n
foo
is evaluated only once, whether or not it is a variable or a more complex expression:I've also cut out a pair of brackets, because unary
*
has lower precedence than binary*
.Thanks to @pillmuncher for pointing out that this can be extended with
izip_longest
to handle lists with an odd number of elements:(See: http://docs.python.org/library/itertools.html#itertools.izip_longest )
只需将每个逗号分开,然后将其组合回来:
Just split on every comma, then combine it back:
像这样
Like this