【发布时间】:2014-03-31 16:41:01
【问题描述】:
我需要用逗号替换两个数字之间的空格
15.30 396.90 => 15.30,396.90
在 PHP 中使用:
'/(?<=\d)\s+(?=\d)/', ','
如何在 Python 中做到这一点?
【问题讨论】:
-
在
php中我会使用strtr。 :P
我需要用逗号替换两个数字之间的空格
15.30 396.90 => 15.30,396.90
在 PHP 中使用:
'/(?<=\d)\s+(?=\d)/', ','
如何在 Python 中做到这一点?
【问题讨论】:
php 中我会使用strtr。 :P
有几种方法可以做到这一点(对不起,Zen of Python)。使用哪一个取决于您的输入:
>>> s = "15.30 396.90"
>>> ",".join(s.split())
'15.30,396.90'
>>> s.replace(" ", ",")
'15.30,396.90'
或者,例如使用re,这样:
>>> import re
>>> re.sub("(\d+)\s+(\d+)", r"\1,\2", s)
'15.30,396.90'
【讨论】:
replace operations 使其比 split/join 操作更快。)
您可以在 Python 中使用与 re module 相同的正则表达式:
import re
s = '15.30 396.90'
s = re.sub(r'(?<=\d)\s+(?=\d)', ',', s)
【讨论】: