Multi line string with arguments. How to declare?

You could abuse the line continuation properties of the parenthesis ( and the comma ,.

cmd = """line %d
      line %d
      line %d""" % (
      1,
      2,
      3)

You could use the str.format() function, that allows named arguments, so:

'''line {0}
line {1}
line {2}'''.format(1,2,3)

You could of course extend this using Python's *args syntax to allow you to pass in a tuple or list:

args = (1,2,3)
'''line {0}
line {1}
line {2}'''.format(*args)

If you can intelligently name your arguments, the most robust solution (though the most typing-intensive one) would be to use Python's **kwargs syntax to pass in a dictionary:

args = {'arg1':1, 'arg2':2, 'arg3':3}
'''line {arg1}
line {arg2}
line {arg3}'''.format(**args)

For more information on the str.format() mini-language, go here.

Tags:

Python