将元组解包为 'format()' 字符串
Unpack tuple to 'format()' string
我有 6 个 int 值的元组,我想用指定的分隔符打印它们...
tuple_code = (10, 20, 30, 40, 11, 117)
..并想用不同的分隔符将它们打印到字符串:
10-20:30.40.11*117
在这种情况下如何正确解包元组?到目前为止我所做的对我来说看起来有点乱。
def to_readable_format(self):
i_code = iter(self.code)
code = "{}-{}:{}.{}.{}*{}".format(str(next(i_code)), str(next(i_code)),
str(next(i_code)), str(next(i_code)),
str(next(i_code)), str(next(i_code)), )
return code
像code = "{}-{}:{}.{}.{}*{}".format(*self.code)
一样使用argument unpacking syntax。如果您的所有元组条目都是整数,则无需显式转换为 str
。
可以直接使用解包操作符*
:
def to_readable_format(tpl):
# i_code = iter(self.code)
code = "{}-{}:{}.{}.{}*{}".format(*tpl)
return code
to_readable_format(tuple_code)
输出:
'10-20:30.40.11*117'
我有 6 个 int 值的元组,我想用指定的分隔符打印它们...
tuple_code = (10, 20, 30, 40, 11, 117)
..并想用不同的分隔符将它们打印到字符串:
10-20:30.40.11*117
在这种情况下如何正确解包元组?到目前为止我所做的对我来说看起来有点乱。
def to_readable_format(self):
i_code = iter(self.code)
code = "{}-{}:{}.{}.{}*{}".format(str(next(i_code)), str(next(i_code)),
str(next(i_code)), str(next(i_code)),
str(next(i_code)), str(next(i_code)), )
return code
像code = "{}-{}:{}.{}.{}*{}".format(*self.code)
一样使用argument unpacking syntax。如果您的所有元组条目都是整数,则无需显式转换为 str
。
可以直接使用解包操作符*
:
def to_readable_format(tpl):
# i_code = iter(self.code)
code = "{}-{}:{}.{}.{}*{}".format(*tpl)
return code
to_readable_format(tuple_code)
输出:
'10-20:30.40.11*117'