Search code examples
python-3.xstring-formatting

String formatting in Python


How do I format the following numbers that are in vector?

For an instance, numbers which I have:

23.02567

0.025679

and I would like to format to this:

0.230256700+E02

0.025679000+E00


Solution

  • First, note that this is not the proper way to format numbers in scientific- or engineering-notation. Those numbers should always have exactly one digit in front of the decimal point, unless the exponent is required to be a multiple of 3 (i.e. a power of 1000, corresponding to one of the SI prefixes). If, however, you have to use this format, you could write your own format string for that.

    >>> x, e = 23.02567, 2
    >>> "%f%sE%02d" % (x/10**e, "+" if e >= 0 else "-", abs(e))
    '0.230257+E02'
    >>> x, e = 0.025679, -1
    >>> "%f%sE%02d" % (x/10**e, "+" if e >= 0 else "-", abs(e))
    '0.256790-E01'
    

    This is assuming that the exponent, e, is given. If the exponent does not matter, you could also use the proper %E format and just replace E+ with +E:

    >>> ("%E" % x).replace("E+", "+E").replace("E-", "-E")
    '2.567900-E02'