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\n , B= %s\n",A,B)
/* some processing */
sprint(buf,"C=%d\n",c)
....
...
fprintf(file,buf)
So in the output file we have this kind of o/p:
A= foo B= bar
C= ded
etc...
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 printf
s I have done since the beginning, like in C
.
Python has a %
operator for this.
>>> a = 5
>>> b = "hello"
>>> buf = "A = %d\n , B = %s\n" % (a, b)
>>> print buf
A = 5
, B = hello
>>> c = 10
>>> buf = "C = %d\n" % 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
If I understand your question correctly, format() is what you are looking for, along with its mini-language.
Silly example for python 2.7 and up:
>>> print "{} ...\r\n {}!".format("Hello", "world")
Hello ...
world!
For earlier python versions: (tested with 2.6.2)
>>> print "{0} ...\r\n {1}!".format("Hello", "world")
Hello ...
world!