Home > database >  Unpack tuple to 'format()' string
Unpack tuple to 'format()' string

Time:02-22

I have tuple with 6 int values, and want to print them with specified separators...

tuple_code = (10, 20, 30, 40, 11, 117)

..and want to print them with diffrent separators to string:

10-20:30.40.11*117

How to unpack tuple properly in this case? What I did so far and looks a bit messy for me.

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

CodePudding user response:

Use argument unpacking syntax like code = "{}-{}:{}.{}.{}*{}".format(*self.code). No need to explicitly cast to str if all your tuple entries are integers.

CodePudding user response:

You can use the unpacking operator * directly:

def to_readable_format(tpl):
#        i_code = iter(self.code)
        code = "{}-{}:{}.{}.{}*{}".format(*tpl)
        return code
    
to_readable_format(tuple_code)

Output:

'10-20:30.40.11*117'
  • Related