Skip to main content
Chemistry LibreTexts

1: Formatting

  • Page ID
    206752
  • Formatting in Python 2.5 and earlier

    Until Python 2.6 formatting was done using % operator. We will not be using this method, but it is important to understand it in case you will have to work with code written before the changes.

    Operator Used for
    %s String (or any object with a string representation, like numbers)
    %d Integers
    %f Floating point numbers
    %.<number of digits>f Floating point numbers with a fixed amount of digits to the right of the dot
    %x/%X Integers in hex representation (lowercase/uppercase)
    element = "Oxygen"
    
    atomic_mass = 15.999
    
    print("Atomic mass of %s is %.3fu" % (element, atomic_mass))
    
    Atomic mass of Oxygen is 15.999u
    

    Formatting using string .format() method (Python 2.6 and up)

    To use this method you need to put placeholders that look like a pair of curvy brackets {} in your string. After the string you need to add .format () and indicate the value(s) you want to use instead of the curvy brackets.

    Here is an example:

    element = "Oxygen"
    
    atomic_mass = 15.999
    
    print("Atomic mass of {1} is {0}u".format(atomic_mass,element))
    Atomic mass of Oxygen is 15.999u
    

    Note, that the variables in parentheses are not in the same order they are used in the print statement. We are using positional parameter to indicate which variable goes where. One thing to remember here is that in Python numbering starts with zero. In our example atomic_mass is #0 and element is #1. You can also use other parameters to further customize the output (see Formatting Parameters section).

     

    The following script calculates the pH of a random acid and its salt (base) concentration if you give it the Ka of the acid.  Note the commented out code uses the modules format while the code that is working uses the format function.

    pKa = float(input("Please enter a value for pKa:"))
    import random
    conbasecon = float(random.uniform(0.000,1.000))
    conacidcon = float(random.uniform(0.000,1.000))
    import math
    pH = pKa + math.log((conbasecon/conacidcon), 10)
    # print("*" * 80)
    # print("Your pKa was %.1f"% pKa)
    # print("Your randomly assigned conjugate base concentration is: %.3f"% conbasecon, "M")
    # print("Your randomly assigned conjugate acid concentration is: %.3f"% conacidcon, "M")
    # print("The pH of this solution is: %.3f"% pH)
    
    print("*" * 80)
    print("Your pKa was ",format(pKa,'0.1f'))
    print("Your randomly assigned conjugate base concentration is", format(conbasecon,'.3f'), "M")
    print("Your randomly assigned conjugate acid concentration is",format(conacidcon,'.3f'), "M")
    print("The pH of this solution is {pH}", format(pH,'.3f'))
    print("The ph of the solution is {0:.2f} when pKa is {1:.2f} and the acid concentration\
    is {2:.3f} and the base is {3:.3f}".format(pH,pKa,conbasecon,conacidcon))

     

    Formatting using f.strings (Python 3.6 and up)

    The newest way of formatting is to use a so-called f-string. This method is very similar to the .format(), but instead of specifying the values after the string we can include them in the curly brackets {} in the string itself. You need to add “f” at the beginning of your string to let Python know that you are using this method. See an example below:

    element = "Oxygen"
    
    atomic_mass = 15.999
    
    print(f"Atomic mass of {element} is {atomic_mass}u")
    Atomic mass of Oxygen is 15.999u
    

    Formatting Parameters

    Sometimes you might want to see your output in a certain way (number of digits, aligned right, centered, etc.). Starting with Python 2.6 we can add multiple options to the string to get the output we need. For example, if we only want to see three significant digits we can use the f.string method with some modifications:

    element = "Oxygen"
    
    atomic_mass = 15.999
    
    print(f"Atomic mass of {element} is {atomic_mass:0.1f}u")
    Atomic mass of Oxygen is 16.0u
    

    You can see that Python automatically rounds the number. Let's look at some other parameters we can use in the similar way.

    Option Meaning
    < Left-align within the available space (default for strings)
    > Right-align within the available space
    0 If the width field is preceded by a zero ('0') character, sign-aware zero-padding for numeric types will be enabled
    , Indicates using commas for a thousands separator
    = Forces the padding to be placed after the sign (if any) but before the digits. Only valid for numeric types
    ^ Center within the available space
    + Use a sign for positive and negative numbers
    - Use a sign for negative numbers only
    space Use leading space for positive numbers, and a minus sign for negative numbers

    You can find more information and other common string operators here.

    ______________

     

     

    Format Function

    there appear to be two ways to use the format function


    print("Total salary: ${:.2f}".format(25))
    print("Total salary: $",format(salary,'0.2f'))

    The first allows you to format more than one thing

    print("Total salary: ${:.2f} for {:d} days".format(25,32))

     

     

     

    A variable can be a number, string... and there are different ways to format

    fill - any character can be filled to a given number|
    sign - This could be a +, - or blank space
    align - The alignment could be <, >, ^ or =
    precision - An integer that tells how precisely the value passed to format method has to be formatted.
    type - This specifies the type - binary, octal, exponential, etc. The other types will be listed in the upcoming post, as and when required.
    width - An integer value specifying how wide the value has to be formatted to.

     

     

    Resources:

    https://pyformat.info/#annotations:al8dbkiAEeqQq_f9ta6urw