String .format() method ======================= Basic usage ----------- .. interactive_code_block:: :caption: Pythonic string formatting uses curly brackets {} as placeholders to add and format data within strings. question = 'Life, The Universe, and Everything' answer = 42 print('The Answer to the Ultimate Question of {} is {}.'.format(question, answer)) The two pairs of curly brackets ``{}`` in the string get replaced with the values of the two arguments ``question`` and ``answer`` of the string method ``.format()``. Notice the dot ``.`` that connects the string with its method. The ``.format()`` combines most advantages of the mix of `alternative options <#alternative-options>`__: * **Implicit type conversion**: Any non-string data will be automatically converted to a string. * **Good readabiltiy**: The text with placehoders is separated from the data to be filled in. * **Additional formatting options**: E.g. how many decimals of a float shall be displayed. * **Well supported**: It works with all versions of Python since 2008 (= 2.6 and later) Sequence options ---------------- Defaults ^^^^^^^^ .. interactive_code_block:: # Sequence of placeholders == sequence of method arguments print('{}, {}, {}').format('Life', 'The Universe', 'Everything') If the curly braces ``{}`` are left empty, the number of placeholders has to match the number of arguments and their sqeuences are identical. Indices ^^^^^^^ .. interactive_code_block:: # Same as default print('{0}, {1}, and {2}').format('Life', 'The Universe', 'Everything') # Reversed sequence print('{2}, {1}, and {0}').format('Life', 'The Universe', 'Everything') # Multiple use of arguments print('{1}, {1}, and {1}').format('Life', 'The Universe', 'Everything') # Using a tuple or list as argument l = ['Life', 'The Universe', 'Everything'] print('{0}, {1}, and {2}').format(*l) Indices can be used to alter the sequence or insert argument values multiple times. *Tuples* and *lists* can also be used as argument if they are unpacked with a single asterisk ``*list``. Keywords ^^^^^^^^ .. interactive_code_block:: # Same as default print('{a}, {b}, and {c}').format(a = 'Life', b = 'The Universe', c = 'Everything') # Reversed sequence print('{c}, {b}, and {a}').format(a = 'Life', b = 'The Universe', c = 'Everything') # Multiple use of arguments print('{b}, {b}, and {b}').format(a = 'Life', b = 'The Universe', c = 'Everything') # Using a dictionary as argument d = {'a': 'Life', 'b': 'The Universe', 'c': 'Everything'} print('{a}, {b}, and {c}').format(**d) Keyword arguments can be used to alter the sequence or insert argument values multiple times. *Dictionaries* can also be used as argument if they are unpacked with a double asterisk ``**dict``. Formatting options ------------------ Defaults ^^^^^^^^ .. interactive_code_block:: # String: no change print('{}'.format('Abcdefghijklm')) # Integer: no change print('{}'.format(123456789012345)) # Float: truncated to 12 digits + decimal point print('{}'.format(123.56789012345)) # Float: switch to scientific representation for numbers equal or higher then 10**12 print('{}'.format(1234567890123.4)) Padding & alignment ^^^^^^^^^^^^^^^^^^^ .. interactive_code_block:: :caption: # String padded with spaces to a defined number of characters (default aligment = left) print('{:8}'.format('Abc')) print('{:^8}'.format('Abc')) print('{:>8}'.format('Abc')) # Number padded with spaces to a defined number of characters (default aligment = right) print('{:8}'.format(123)) print('{:^8}'.format(123)) print('{:<8}'.format(123)) # Instead of spaces other characters can be used as well print('{:-<8}'.format('Abc')) print('{:=^8}'.format('Abc')) print('{:>>8}'.format('Abc')) print('{:<>8}'.format(123)) print('{:*^8}'.format(123)) print('{::<8}'.format(123)) Floats ^^^^^^ .. interactive_code_block:: :caption: Formatting options for float # Type set to float: truncated to 10 digits + decimal point print( '{:f}'.format(1234.567890123)) # Type set to float and the output set to use at least 15 characters print( '{:5f}'.format(1234.567890123)) # Rounded and truncated to 3 digits after the decimal point print('{:.3f}'.format(1234.567890123)) # Rounded to 3 decimal places, 15 characters (including decimal point) print('{:15.3f}'.format(1234.567890123)) # Rounded to 3 decimal places, with sign print('{:+.3f}'.format(1234.567890123)) # Rounded to 0 decimal places print('{:.0f}'.format(1234.567890123)) Alternative options ------------------- String concatenation ^^^^^^^^^^^^^^^^^^^^ .. interactive_code_block:: :caption: Strings can also be added (= concatenated) together with the '+' operator. question = 'Life, The Universe, and Everything' answer = 42 print('The Answer to the Ultimate Question of ' + question + ' is ' + str(answer) + '.') Since only strings can be added to strings but not e.g. integers, explicit type conversion with the built-in ``str()`` function will be necessary for any non-string values. Python 2 style % ^^^^^^^^^^^^^^^^ .. interactive_code_block:: :caption: Python 2 originally used a different syntax. question = 'Life, The Universe, and Everything' answer = 42 print('The Answer to the Ultimate Question of %s is %d.' % (question, answer)) Before the ``.format()`` method was added to Python versions 2.6 and 3.0 in 2008, different placeholders (e.g. ``%s`` for string values and ``%d`` for decimal integers) and ``%`` instead of ``.format()`` had to be used. .. Exists at least sinde Python 1.4 (October 25, 1996) https://docs.python.org/release/1.4/lib/node11.html Template strings ^^^^^^^^^^^^^^^^ .. interactive_code_block:: from string import Template question = 'Life, The Universe, and Everything' answer = 42 template = Template('The Answer to the Ultimate Question of $q is $a.') print(template.substitute(q = question, a = answer)) In 2004 the ``Template()`` class was added to the ``string`` module from the standard library to satisfy the `Python enhancement proposal (PEP) 292 `__. |br| NOTE: Since the `in-browser version of Python`_ used here supports only a subset of the standard library which does not include the ``Template()`` class, **clicking 'Run' will throw an error**. .. PEP --- https://www.python.org/dev/peps/pep-0292/ Date ---- Commits on Aug 25, 2004 PEP 292 classes Template and SafeTemplate are added to the string module https://github.com/python/cpython/commit/8bee76106e8da9fd6011432d2f60861a94c623db#diff-f059a6f5063e6fac8156e2b670ac0ceeb265abf633d048217bc676dcd4192f2a Python 3.6 f-string ^^^^^^^^^^^^^^^^^^^ .. interactive_code_block:: :caption: Python 3.6+ f-String formatting. question = 'Life, The Universe, and Everything' answer = 42 print(f'The Answer to the Ultimate Question of {question} is {answer}.') In 2016 formatted string literals (also called f-strings) have been added as another option, but they are not supported by any Python version prior to 3.6. Notice the ``f`` that precedes the string literal. References ---------- https://docs.python.org/3/library/string.html#formatstrings https://realpython.com/python-string-formatting/ Examples ^^^^^^^^ https://pyformat.info .. https://www.python.org/download/releases/2.6/ https://www.python.org/download/releases/3.0/ https://docs.python.org/3.6/whatsnew/changelog.html#python-3-6-0-final https://docs.python.org/3/library/string.html#formatstrings https://docs.python.org/3/library/string.html#formatspec https://realpython.com/python-string-formatting/ .. _in-browser version of Python: http://skulpt.org