Pass *args to string.format in Python?

Question:

Is it possible to pass *args to string.format? I have the following function:

@classmethod
def info(cls, component, msg, *args):
    """Log an info message"""
    cls.__log(cls.Level.INFO, component, msg, args)

@classmethod
def __log(cls, level, component, msg, *args):
    """Log a message at the requested level"""
    logging.getLogger("local").log(level, " - ".join([component, msg.format(args)]))

When I try unit test it with LogCapture I get the following:

def test_logWithArgs(self):
    Logger.level(Logger.Level.INFO)
    with LogCapture(level=Logger.Level.INFO) as lc:
        Logger.info("MyComponent", "{0}", "TestArg")
        lc.check(("local", "INFO", "MyComponent - TestArg"))


AssertionError: Sequence not as expected:

same:
()

first:
(('local', 'INFO', 'MyComponent - TestArg'),)

second:
(('local', 'INFO', "MyComponent - (('TestArg',),)"),)
Asked By: Graeme

||

Answers:

I think what you want to do is

msg.format(*args)
Answered By: Gustav Larsson

Yes, it can be done by unpacking like this:

>>> a = (1, 2, 3, 4)
>>> "{0}{1}{2}{3}".format(*a)
'1234'
Answered By: Ashwini Chaudhary
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.