37 - with a regular expression for all floating point format string

The number of times a regular expression search string in all floating-point and floating-point format these, to two decimal places, most floating-point numbers formatted replace the original floating-point numbers, the result of simultaneous output to replace and replacement . Required to achieve a single statement

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

38 - URL to extract the HTML page

Ruo
Published 142 original articles · won praise 148 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_29339467/article/details/104527157