Search code examples
pythonprintfstring-formatting

How to print a C format in python


A python newbie question:

I would like to print in python with the c format with a list of parameters:

agrs = [1,2,3,"hello"]
string = "This is a test %d, %d, %d, %s"

How can I print using python as:

This is a test 1, 2, 3, hello

Thanks.


Solution

  • Strings overload the modulus operator, %, for printf-style formatting, and special case tuples for formatting using multiple values, so all you need to do is convert from list to tuple:

    print(string % tuple(agrs))