string – sprintf like functionality in Python

string – sprintf like functionality in Python

Python has a % operator for this.

>>> a = 5
>>> b = hello
>>> buf = A = %dn , B = %sn % (a, b)
>>> print buf
A = 5
 , B = hello

>>> c = 10
>>> buf = C = %dn % 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 {} ...rn {}!.format(Hello, world)
Hello ...
 world!

For earlier python versions: (tested with 2.6.2)

>>> print {0} ...rn {1}!.format(Hello, world)
Hello ...
 world!

string – sprintf like functionality in Python

Im not completely certain that I understand your goal, but you can use a StringIO instance as a buffer:

>>> import StringIO 
>>> buf = StringIO.StringIO()
>>> buf.write(A = %d, B = %sn % (3, bar))
>>> buf.write(C=%dn % 5)
>>> print(buf.getvalue())
A = 3, B = bar
C=5

Unlike sprintf, you just pass a string to buf.write, formatting it with the % operator or the format method of strings.

You could of course define a function to get the sprintf interface youre hoping for:

def sprintf(buf, fmt, *args):
    buf.write(fmt % args)

which would be used like this:

>>> buf = StringIO.StringIO()
>>> sprintf(buf, A = %d, B = %sn, 3, foo)
>>> sprintf(buf, C = %dn, 5)
>>> print(buf.getvalue())
A = 3, B = foo
C = 5

Leave a Reply

Your email address will not be published.