python格式化字符串时, 可以通过引用变量名、类属性等进行格式化,例如:
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
上面的方法,传入所有格式化需要的参数,少传就会报错,例如:
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N')
Traceback (most recent call last):
...
KeyError: 'longitude'
对于某些情况下,没有办法传入所有参数,有另一种方法safe_substitute:
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
更多参考官方文档: docs.python.org/zh-cn/3.8/l…
今天收到一个新的需求,已经有了一个格式化字符串,解析字符串,把对应的格式化时传入的key的值再反解析出来,搜了一下没有搜到太好的办法,网上说的方法有的是自己使用split解析,有的用re模块来匹配,但是用的groups来按照index来取值,不灵活。
翻了一下python官方文档,re模块,有这个功能
(?P…)
- (命名组合)类似正则组合,但是匹配到的子串组在外部是通过定义的 name 来获取的。组合名必须是有效的Python标识符,并且每个组合名只能用一个正则表达式定义,只能定义一次。一个符号组合同样是一个数字组合,就像这个组合没有被命名一样。
测试了一下没有问题,符合需求:(注意:(?P…)是一个整体,括号也不能少)
>>> import re
>>> match_result = re.search('Coordinates: (?P<latitude>.*), (?P<longitude>.*)', 'Coordinates: 37.24N, -115.81W')
>>> match_result.group("latitude")
'37.24N'
>>> match_result.group("longitude")
'-115.81W'
>>> match_result.groupdict()
{'latitude': '37.24N', 'longitude': '-115.81W'}
更多参考官方文档: docs.python.org/zh-cn/3.8/l…