Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 446
username_4567 Avatar asked Feb 20 '12 18:02

username_4567


People also ask

How do you split a string at every comma in Python?

You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by comma in Python, pass the comma character "," as a delimiter to the split() function. It returns a list of strings resulting from splitting the original string on the occurrences of "," .

How do you split a string at every comma?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);

How do you split a string after in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Can we pass multiple separators in split () Python?

Split the string with multiple separatorsWe can also specify multiple characters as separators. For this, we need to make use of the re module of Python and import the re. split() function.


2 Answers

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?

like image 166
Useless Avatar answered Nov 14 '22 23:11

Useless


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 )

like image 21
Marcin Avatar answered Nov 14 '22 23:11

Marcin