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 Pyt
To insert into a very long string it is nice to use names for the different arguments, instead of hoping they are in the right positions. This also makes it easier to replace multiple recurrences.
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
Taken from Format examples, where all the other Format
-related answers are also shown.
I'm 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 = %s\n" % (3, "bar"))
>>> buf.write("C=%d\n" % 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 you're 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 = %s\n", 3, "foo")
>>> sprintf(buf, "C = %d\n", 5)
>>> print(buf.getvalue())
A = 3, B = foo
C = 5
If you want something like the python3 print function but to a string:
def sprint(*args, **kwargs):
sio = io.StringIO()
print(*args, **kwargs, file=sio)
return sio.getvalue()
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}\n"
or without the '\n'
at the end:
def sprint(*args, end='', **kwargs):
sio = io.StringIO()
print(*args, **kwargs, end=end, file=sio)
return sio.getvalue()
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}"
Use the formatting operator % : buf = "A = %d\n , B= %s\n" % (a, b) print >>f, buf
You can use string formatting:
>>> a=42
>>> b="bar"
>>> "The number is %d and the word is %s" % (a,b)
'The number is 42 and the word is bar'
But this is removed in Python 3, you should use "str.format()":
>>> a=42
>>> b="bar"
>>> "The number is {0} and the word is {1}".format(a,b)
'The number is 42 and the word is bar'