Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace space character between two numbers

I need to replace space with comma between two numbers

15.30 396.90 => 15.30,396.90

In PHP this is used:

'/(?<=\d)\s+(?=\d)/', ','

How to do it in Python?

like image 433
blackmamba Avatar asked Mar 31 '14 16:03

blackmamba


2 Answers

There are several ways to do it (sorry, Zen of Python). Which one to use depends on your input:

>>> s = "15.30 396.90"
>>> ",".join(s.split())
'15.30,396.90'
>>> s.replace(" ", ",")
'15.30,396.90'

or, using re, for example, this way:

>>> import re
>>> re.sub("(\d+)\s+(\d+)", r"\1,\2", s)
'15.30,396.90'
like image 153
alecxe Avatar answered Sep 29 '22 21:09

alecxe


You can use the same regex with the re module in Python:

import re
s = '15.30 396.90'
s = re.sub(r'(?<=\d)\s+(?=\d)', ',', s)
like image 31
Andrew Clark Avatar answered Sep 29 '22 21:09

Andrew Clark