user1919
user1919

Reputation: 3938

Pythonic way to replace every second comma of string with space

I have a string which looks like this:

coords = "86.2646484375,23.039297747769726,87.34130859375,22.59372606392931,88.13232421875,24.066528197726857"

What I want is to bring it to this format:

coords = "86.2646484375,23.039297747769726 87.34130859375,22.59372606392931 88.13232421875,24.066528197726857"

So in every second number to replace the comma with a space. Is there a simple, pythonic way to do this.

Right now I am trying to do it with using the split function to create a list and then loop through the list. But it seems rather not straightforward.

Upvotes: 4

Views: 4770

Answers (3)

Daniel
Daniel

Reputation: 42748

The pythonic way is to split the string and join it again, with the alternating delimiters:

from itertools import chain, cycle, izip
coords = ''.join(chain.from_iterable(izip(coords.split(','), cycle(', '))))

Upvotes: 2

John1024
John1024

Reputation: 113834

First let's import the regular expression module and define your coords variable:

>>> import re
>>> coords = "86.2646484375,23.039297747769726,87.34130859375,22.59372606392931,88.13232421875,24.066528197726857"

Now, let's replace every second comma with a space:

>>> re.sub('(,[^,]*),', r'\1 ', coords)
'86.2646484375,23.039297747769726 87.34130859375,22.59372606392931 88.13232421875,24.066528197726857'

The regular expression (,[^,]*), looks for pairs of commas. The replacement text, r'\1 ' keeps the first comma but replaces the second with a space.

Upvotes: 15

zw324
zw324

Reputation: 27180

This sort of works:

>>> s = coords.split(',')
>>> s
['86.2646484375', '23.039297747769726', '87.34130859375', '22.59372606392931', '88.13232421875', '24.066528197726857']
>>> [','.join(i) for i in zip(s[::2], s[1::2])]
['86.2646484375,23.039297747769726', '87.34130859375,22.59372606392931', '88.13232421875,24.066528197726857']

Upvotes: 3

Related Questions