How can I format the string according to its length at runtime?

Tom Good Tom_Good1 at excite.com
Wed Jun 20 01:08:15 CEST 2001


ed_tsang at yahoo.com wrote in message news:<mailman.992971110.11976.python-list at python.org>...
> How can I format the string but according to the length it has?
> 
> I have the following code:
> 
> l = 6 - len(str(values))
> printwrite(trcfile, "Rx value = %-5s (0x%-6X)-  OK\n"%(str(values), 
> values),tag )
> 
> Currently I displays:
> 
> Check       : TPreason = 120 (0x78)                   Rx value = 
> 120   (0x78    )-  OK
> 
> function printwrite is just a wrapper function of sys.file.write and 
> print that prints the info to the screen, or a trace window and to a 
> file accordingly. The string formmating is he same as the python doc.
> 
> values in the above code is a integer number.
> The above statement tries to diplay the input string [ from str
> (values ] and convert values to be displayed as hexadecimal. 
> 
> My problem is when it displayed in hexadecimal, there are extra 
> spacing because it of the statement 0x%-6X when the lengeth of values 
> is 3. But I will no know in advance what is the length of values, it 
> can reach 6. How can I dynmically alter the number of spaces in this 
> case?
> 

Try something like this:

lengthOfHexString = len("%x" % values)
padding = " " * (6 - lengthOfHexString)
print "Rx value = %-5s (0x%X)%s-  OK\n" %(str(values), values, padding)



More information about the Python-list mailing list