Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to replace every second comma of string with space

Tags:

python

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.

like image 483
user1919 Avatar asked Nov 30 '22 23:11

user1919


2 Answers

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.

like image 192
John1024 Avatar answered Dec 02 '22 11:12

John1024


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']
like image 39
zw324 Avatar answered Dec 02 '22 13:12

zw324