What do you use to format a string,%, or format?

7

Use "%" or "format" ? I think the latter is more recent, but is there any other aspect to be taken into account when deciding which one to use?

    
asked by anonymous 11.12.2017 / 22:40

1 answer

10
  

For 3.6+ versions, use f-strings for the interpolation: How to do tween string in Python?

For versions 3+, earlier than 3.6, always prefer to use the format method, it was set just to replace % - to version 3.6 or higher, read Formatted string literals . The PEP that suggested such a change was PEP 3101:

PEP 3101 - Advanced String Formatting

And some of the points that led to such a change are:

  • The % operator is a binary operator, so it will always receive two parameters. The first one is already reserved for the string that will be formatted, so the language is limited to passing all the values of the format through the second parameter;

    This has some implications:

    • The parameter that has the formatting values will necessarily be a composite type, as it must have the ability to store multiple values;

      >>> string % parameters
      
    • It is limited to always using only positional parameters, when passing them through a tuple, or named parameters, when passing them through a dictionary, but never both concurrently;

      >>> '%s %s' % ('john', 'doe')  # posicional
      john doe
      
      >>> '%(first)s %(last)s' % {'first': 'john', 'last': 'doe'}  # nomeado
      john doe
      
    • >>> 5 % 2  # Calcula o resto da divisão
      1
      
      >>> string % parameters  # Formata string????
      
  • You can not use language tools such as tuple deconstructing or dict deconstructing to ease the passing of values;

    >>> name = ['john', 'doe']
    >>> '%s %s' % (*name)
    SyntaxError: invalid syntax
    
  • Other than that, other features were added to the new style when using the format method:

  • Use positional parameters, but use them in random order;

    >>> '{1}, {0}'.format('john', 'doe')
    doe, john
    
  • Define spacing in the string by replacing the character to be displayed: in the old style, a blank is always displayed;

    >>> '{:_<10}'.format('john')
    john______
    
  • Centralize content with reference to available space;

    >>> '{:_^10}'.format('john')
    +++john+++
    
  • By using flagged numbers, you can control the position of the signal;

    >>> '{:=5d}'.format(-3)
    -   3
    >>> '{:=+5d}'.format(3)
    +   3
    
  • The format method accepts named parameters to define the values, not depending more on dictionaries or tuples;

    >>> '{first} {last}'.format(first='john', last='doe')
    john doe
    

    >>> name = ('john', 'doe')
    >>> '{0} {1}'.format(*name)
    john doe
    
    >>> name = {'first': 'john', 'last': 'doe'}
    >>> '{first} {last}'.format(**name)
    john doe
    
  • You can access values directly from string ;

    >>> john = {'first': 'john', 'last': 'doe'}
    >>> '{name[first]} {name[last]}'.format(name=john)
    john doe
    
  • Similarly, you can access object attributes;

    >>> 'Nome do arquivo: {0.name}'.format(open('arquivo.txt'))
    Nome do arquivo: arquivo.txt
    
  • It is possible for objects to take control of their own formatting, just as with the object datetime.datetime ;

    >>> from datetime import datetime
    >>> '{:%Y-%m-%d %H:%M}'.format(datetime.now())
    2017-12-11 20:52
    

    This is possible because the format method will search for the __format__ method of the object;

  • You can parameterize the format itself with its values;

    >>> '{:_{align}{width}}'.format('john', align='^', width='10')
    ___john___
    >>> '{:_{align}{width}}'.format('john', align='>', width='10')
    ______john
    
  • Other references

    [1] Using% and .format () for great good!

    [2] Class string.template

    [3] List of emails: String formating operations in python 3k

    a>

        
    11.12.2017 / 23:35