sprintf like functionality in Python


I would like to create a string buffer to do lots of processing, format and finally write the buffer in a text file using a C-style sprintf functionality in Python. Because of conditional statements, I can’t write them directly to the file.

e.g pseudo code:

sprintf(buf,"A = %d
 , B= %s
/* some processing */

So in the output file we have this kind of o/p:

A= foo B= bar
C= ded

Edit, to clarify my question:
buf is a big buffer contains all these strings which have formatted using sprintf. Going by your examples, buf will only contain current values, not older ones. e.g first in buf I wrote A= something ,B= something later C= something was appended in the same buf, but in your Python answers buf contains only last value, which is not I want - I want buf to have all the printfs I have done since the beginning, like in C.

Answer rating: 184

Python has a % operator for this.

>>> a = 5
>>> b = "hello"
>>> buf = "A = %d
 , B = %s
" % (a, b)
>>> print buf
A = 5
 , B = hello

>>> c = 10
>>> buf = "C = %d
" % c
>>> print buf
C = 10

See this reference for all supported format specifiers.

You could as well use format:

>>> print "This is the {}th tome of {}".format(5, "knowledge")
This is the 5th tome of knowledge

Get Solution for free from DataCamp guru