[Tutor] sprintf-like functionality in Python
alan.gauld at blueyonder.co.uk
Mon Aug 25 19:56:25 EDT 2003
> What I am trying to do is take data with comes into my program as
> convert it to ASCII. For instance, I get:
> together in Python. In C, I'd use sprintf. In short, I start with
> 0x35 and need to translate it to the integer 25. Thanks.
Can you show how you'd use sprintf in C?
Because I'm afraid the explanation confused me!
the equivalent of sprintf in Python is the string format operator %:
mystring = "%s %d\t%3.2f %-8s" % ("Values:",42,56.89732,"tot")
or to make it clearer(?) whats happening:
fmtString = "%s %d\t%3.2f %-8s" # %N markers the same as in C
vals = ("Values:",42,56.89732,"tot") # tuple, one value per marker
myString = fmtString % vals # combine them with % operator
Python also provides some extra goodies in that you can use
keywords to identify the substitution values and pluck them
from a dictionary etc.
If that doesn't help send the equivalent C sprintf code and
we'll try to translate.
More information about the Tutor