V2CE – 37 – 用正则表达式格式化字符串中所有的浮点数

用正则表达式查找字符串中所有的浮点数,并格式化这些浮点数,保留小数点后两位,最将格式化后的浮点数替换原来的浮点数,同时输出替换后的结果和替换的次数。要求用一条语句实现

import re

'''
1. 表示浮点数的正则表达式 -?\d+(\.\d+)?
2. 格式化浮点数 format
3. 如何替换原来的浮点数 
    sub: 只返回结果
    subn: 返回一个元组
          元组第一个元素返回替换后的结果,第二个元素返回替换的次数
'''

result = re.subn('-?\d+(\.\d+)?', '##', 'PI is 3.14, e is 2.71, 1 + 1 = 2')
print(result)
print(result[0])
print(result[1])

('PI is ##, e is ##, ## + ## = ##', 5)

PI is ##, e is ##, ## + ## = ##

5

def fun(matched):
    return '<' + matched.group() + '>'


result = re.subn('-?\d+(\.\d+)?', fun, 'PI is 3.14, e is 2.71, 1 + 1 = 2')
print(result)
print(result[0])
print(result[1])

('PI is <3.14>, e is <2.71>, <1> + <1> = <2>', 5)

PI is <3.14>, e is <2.71>, <1> + <1> = <2>

5

def fun(matched):
    return format(float(matched.group()), '.1f')


result = re.subn('-?\d+(\.\d+)?', fun, 'PI is 3.14, e is 2.71, 1 + 1 = 2')
print(result)
print(result[0])
print(result[1])

('PI is 3.1, e is 2.7, 1.0 + 1.0 = 2.0', 5)

PI is 3.1, e is 2.7, 1.0 + 1.0 = 2.0

5

正文完