我可以用str.format(**arg)格式化字符串,如下所示:

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

But can i use it in reverse to check whether a string adheres to certain format? 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
_

最佳答案

在我用parse安装之后,有一个pip模块,称为“format()的反面”:

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

关于python - 可以使用str.format(** arg)检查格式吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27194939/

10-12 12:28
查看更多