parse()与format()相反
parse的Python项目详细描述
格式语法
Anonymous支持格式字符串语法的基本版本 (固定位置),命名和格式化字段:
{[field name]:[format spec]}
字段名必须是有效的python标识符,包括虚线名称; 元素索引表示字典(例如,请参见下面的内容)。
也不支持编号字段:解析的结果将包括 已解析字段的解析顺序。
将字段转换为字符串以外的类型是基于 输入格式规范,它反映 format() 行为。 没有"!"字段转换,例如 format() 具有。
一些简单的parse()格式字符串示例:
>>> parse("Bring me a {}", "Bring me a shrubbery") <Result ('shrubbery',) {}> >>> r = parse("The {} who say {}", "The knights who say Ni!") >>> print(r) <Result ('knights', 'Ni!') {}> >>> print(r.fixed) ('knights', 'Ni!') >>> r = parse("Bring out the holy {item}", "Bring out the holy hand grenade") >>> print(r) <Result () {'item': 'hand grenade'}> >>> print(r.named) {'item': 'hand grenade'} >>> print(r['item']) hand grenade >>> 'item' in r True
请注意,中的 仅在已命名字段的情况下有效。虚线名称和索引 虽然应用程序必须对结果有额外的意义,但仍有可能:
>>> r = parse("Mmm, {food.type}, I love it!", "Mmm, spam, I love it!") >>> print(r) <Result () {'food.type': 'spam'}> >>> print(r.named) {'food.type': 'spam'} >>> print(r['food.type']) spam >>> r = parse("My quest is {quest[name]}", "My quest is to seek the holy grail!") >>> print(r) <Result () {'quest': {'name': 'to seek the holy grail!'}}> >>> print(r['quest']) {'name': 'to seek the holy grail!'} >>> print(r['quest']['name']) to seek the holy grail!
如果要匹配的文本中有大括号,则可以通过包含 格式字符串中的双大括号 {{ 或 } ,就像format()一样。