可以使用str.format(** arg)来检查格式吗?

时间:2014-11-28 19:33:02

标签: python c regex string string-formatting

我可以使用str.format(**arg)格式化字符串:

>>> a, b, c = 1123,242,32364
>>> "{}_{}_{}".format(a,b,c)
'1123_242_32364'

但我可以反过来使用它来检查一个字符串是否符合某种格式? E.g。

>>> "{}_{}_{}".check_format("a_bc_def")
True
>>> a,b,c = "{}_{}_{}".deformat("a_bc_def")
>>> a
a
>>> b
bc
>>> c
def

>>> "{}_{}_{}".chcek_format("_____")
True
>>> a,b,c = "{}_{}_{}".deformat("_____")
>>> a == b == c == "_"
True

>>> "{}_{}_{}".chcek_format("_1ad_das__")
True
>>> a,b,c = "{}_{}_{}".deformat("_1ad_das__")
>>> a
_1ad
>>> b
das
>>> c
_

1 个答案:

答案 0 :(得分:5)

parse模块,描述为"与格式()相反。"我用pip安装后:

>>> from parse import *
>>> parse("{}_{}_{}", "a_bc_def")
<Result ('a', 'bc', 'def') {}>
>>> a,b,c  = parse("{}_{}_{}", "_1ad_das__")
>>> a
'_1ad'
>>> b
'das'
>>> c
'_'