username_4567
username_4567

Reputation: 4903

string splitting after every other comma in string in python

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

Upvotes: 6

Views: 7371

Answers (5)

Joel Cornett
Joel Cornett

Reputation: 24788

Just split on every comma, then combine it back:

splitList = someString.split(",")
joinedString = ','.join([splitList[i - 1] + splitList[i] for i in range(1, len(splitList), 2)]

Upvotes: 0

Marcin
Marcin

Reputation: 49846

Split, and rejoin.

So, to split:

In [173]: "a,b,c,d".split(',')
Out[173]: ['a', 'b', 'c', 'd']

And to rejoin:

In [193]: z = iter("a,b,c,d".split(','))
In [194]: [a+b for a,b in zip(*([z]*2))]
Out[194]: ['ab', 'cd']

This works because ([z]*2) is a list of two elements, both of which are the same iterator z. Thus, zip takes the first, then second element from z 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:

In [195]: [a+b for a,b in zip(*[iter("a,b,c,d".split(','))]*2)]
Out[195]: ['ab', 'cd']

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:

In [214]: from itertools import izip_longest

In [215]: [a+b for a,b in izip_longest(*[iter("a,b,c,d,e".split(','))]*2, fillvalue='')]
Out[215]: ['ab', 'cd', 'e']

(See: http://docs.python.org/library/itertools.html#itertools.izip_longest )

Upvotes: 2

Useless
Useless

Reputation: 67743

It's probably easier to split on every comma, and then rejoin pairs

>>> original = 'a,1,b,2,c,3'
>>> s = original.split(',')
>>> s
['a', '1', 'b', '2', 'c', '3']
>>> alternate = map(''.join, zip(s[::2], s[1::2]))
>>> alternate
['a1', 'b2', 'c3']

Is that what you wanted?

Upvotes: 8

nullpotent
nullpotent

Reputation: 9260

str = "a,b,c,d".split(",")
print ["".join(str[i:i+2]) for i in range(0, len(str), 2)]

Upvotes: 0

Tristian
Tristian

Reputation: 3512

Like this

"a,b,c,d".split(',')

Upvotes: -3

Related Questions