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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With