Python Language


String Formatting All Versions

Python 2.x

2.0
2.1
2.2
2.3
2.4
2.5
2.6
2.7

Python 3.x

3.0
3.1
3.2
3.3
3.4
3.5
3.6

This draft deletes the entire topic.

Introduction

When storing and transforming data for humans to see, string formatting can become very important. Python offers a wide variety of string formatting methods which are outlined in this topic.

expand all collapse all

Examples

  • 34
    foo = 1
    bar = 'bar'
    baz = 3.14
    

    You can use str.format to format output. Bracket pairs are replaced with arguments in the order in which the arguments are passed:

    print('{}, {} and {}'.format(foo, bar, baz))
    # Out: "1, bar and 3.14"
    

    Indexes can also be specified inside the brackets. The numbers correspond to indexes of the arguments passed to the str.format function (0-based).

    print('{0}, {1}, {2}, and {1}'.format(foo, bar, baz))
    # Out: "1, bar, 3.14, and bar"
    print('{0}, {1}, {2}, and {3}'.format(foo, bar, baz))
    # Out: index out of range error
    

    Object fields can be referenced when passed into str.format:

    class AssignValue(object):
        def __init__(self, value):
            self.value = value
    my_value = AssignValue(6)
    print('My value is: {0.value}'.format(my_value)) #"0" is optional
    # Out: "My value is: 6"
    

    Dictionary keys can also be used:

    my_dict = {'key': 6, 'other_key': 7}
    print("My key is: {key}".format(**my_dict))
    # Out: My key is: 6
    

    Named arguments can be used as well:

    print("X value is: {x_val}. Y value is: {y_val}.".format(x_val=2, y_val=3))
    # Out: "X value is: 2. Y value is: 3."
    

    Note: Some online Python 2 samples use % to format strings instead of str.format. % is not recommended and will eventually be deprecated. Always use the str.format function.

    In addition to argument indexes, you can also include a format specification inside the curly brackets. This is an expression that follows special rules and must be preceded by a colon (:). An example of format specification is the alignment directive :~^20 (^ stands for center alignment, total width 20, fill with ~ character):

    '{:~^20}'.format('centered')
    # Out: '~~~~~~centered~~~~~~'
    
  • 28
    Python 2.x2.6

    The format() method can be used to change the alignment of the string. You have to do it with a format expression of the form :[fill_char][align_operator][width] where align_operator is one of:

    • < forces the field to be left-aligned within width.
    • > forces the field to be right-aligned within width.
    • ^ forces the field to be centered within width.
    • = forces the padding to be placed after the sign (numeric types only).

    fill_char (if omitted default is whitespace) is the character used for the padding.

    '{:~<9s}, World'.format('Hello')
    # 'Hello~~~~, World'
    
    '{:~>9s}, World'.format('Hello')
    # '~~~~Hello, World'
    
    '{:~^9s}'.format('Hello')
    # '~~Hello~~'
    
    '{:0=6d}'.format(-123)
    # Out: '-00123'
    

    Note: you could achieve the same results using the string functions ljust(), rjust(), center(), zfill(), however these functions are deprecated since version 2.5.

  • 23

    Literal format strings were introduced in PEP 498 (Python3.6 and upwards), allowing you to prepend f to the beginning of a string literal to effectively apply .format to it with all variables in the current scope.

    >>> foo = 'bar'
    >>> f'Foo is {foo}'
    'Foo is bar'
    

    This works with more advanced format strings too, including alignment and dot notation.

    >>> f'{foo:^7s}'
    '  bar  '
    

    Note: The f'' does not denote a particular type like b'' for bytes or u'' for unicode in python2. The formating is immediately applied, resulting in a normal stirng.

    The format strings can also be nested:

    >>> price = 478.23
    >>> f"{f'${price:0.2f}':*>20s}"
    '*************$478.23'
    

    The expressions in an f-string are evaluated in left-to-right order. This is detectable only if the expressions have side effects:

    >>> def fn(l, incr):
    ...    result = l[0]
    ...    l[0] += incr
    ...    return result
    ...
    >>> lst = [0]
    >>> f'{fn(lst,2)} {fn(lst,3)}'
    '0 2'
    >>> f'{fn(lst,2)} {fn(lst,3)}'
    '5 7'
    >>> lst
    [10]
    
Please consider making a request to improve this example.

Syntax

  • "{}".format(42) ==> "42"
  • "{0}".format(42) ==> "42"
  • "{0:.2f}".format(42) ==> "42.00"
  • "{0:.0f}".format(42.1234) ==> "42"
  • "{answer}".format(no_answer=41, answer=42) ==> "42"
  • "{answer:.2f}".format(no_answer=41, answer=42) ==> "42.00"
  • "{answer} = {answer}".format(answer=42) ==> "42 = 42"
  • ' '.join(['stack', 'overflow']) ==> 'stack overflow'

Parameters

Parameters

Remarks

  • Should check out PyFormat.info for a very thorough and gentle introduction/explanation of how it works.
Still have a question about String Formatting? Ask Question

Topic Outline