user1919 user1919 - 1 year ago 94
Python Question

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download