Changing the Formatting String from% to Alternate Characters?


In python 2.6, is there a way to specify an alternate character other than % for string formatting operations? Or is the % char hardcoded in the python interpreter?

For example, to generate a string that looks like this:


I currently have to do this:

str = "%s%%02%s%%03%s" % (param1, param2, param3)

What I'd like to be able to do is substitute, say, ^ for % and be able to do:

str = "^s%02^s%03^s" ^ (param1, param2, param3)

which IMO is far more readable.

You can use the new str.format method. It offers more formatting options and is more readable.

>>> '{0}%02{1}%03{2}'.format('a', 'b', 'c')

>>> '{param1} is also {param2}'.format(param1='foo', param2='bar')
'foo is also bar'

>>> '{0[name]} is {0[age]} years old'.format({'name': 'Bob', 'age': 42})
'Bob is 42 years old'

For more information, check the documentation: Format string syntax