• PYTHON > formater et présenter du texte

      nom = "Waters"
      taille: 1.77
      print("Nom: {}".format(nom)) <=> print(f"Nom: {nom}")
      Nom: Waters
      
      print("Nom: {nom:10s}, Taille: {taille:.3f}m")
      Nom: Waters    , Taille: 1.770m

       

      {:10s} au moins 10 caractères.

      {:.3f} float à trois décimales.

      à droite

      band = "Pink Floyd"
      print("{band:>15}") ->     Pink Floyd

      > alignement à droite, de 15 caractères (15), sans caractère spécifique (donc espaces).

      à gauche

      print("{band:*<15}") -> Pink Floyd*****

      centré

      print(f"{band:.^15}") -> ...Pink Floyd..

       

      heure

      f'il est {datetime.now():%H:%M:%S}' -> il est 10:53:54

       

      "il est %(time)s" % {"time": datetime.now().strftime("%H:%M:%S")} -> il est 10:53:54

       

      Utiliser plusieurs fois le même terme :

      print('{0} {0} {0}'.format('yo')) -> yo yo yo
      print "%(x)s %(x)s %(x)s" % {"x" : "yo"} -> yo yo yo

       

      On peut séparer la représentation des données, pour les nombres :

      a = "{:02}.png"
      a.format(1)  -> 01.png
      a.format(30) -> 30.png

       

      Conversions de base pour les nombres (ici du décimal au binaire) :

      a = "{:b}"
      a.format(50) -> 110010

       

      Cela peut aussi servir :

      vars = ['aaa', 'bbb']
      "a=%s b=%s" % tuple(vars)
      a=aaa b=bbb

       

      "a={} b={}".format(*vars)

       

      If you just want to render the output of str(…) or repr(…) you can use the !s or !r conversion flags.

      In %-style you usually use %s for the string representation but there is %r for a repr(…) conversion.

      '{0!s} {0!r}'.format(Data()) -> str repr

      In Python 3 there exists an additional conversion flag that uses the output of repr(…) but uses ascii(…) instead.

      '{0!r} {0!a}'.format(Data()) -> räpr r\xe4pr

       

      '{:10}'.format('test')
      test

       

      '{:_<10}'.format('test')
      test______

       

      '{:^10}'.format('test')
         test

       

      '{:^6}'.format('zip')
       zip

       

      '{:.5}'.format('xylophone') -> xylop

       

      '{:10.5}'.format('xylophone') -> xylop

       

      '{:d}'.format(42) -> 42

       

      '{:f}'.format(3.141592653589793) -> 3.141593

       

      '{:4d}'.format(42)
        42

       

      '{:06.2f}'.format(3.141592653589793) -> 003.14

       

      '{:04d}'.format(42) -> 0042

       

      '{:+d}'.format(42) -> +42

       

      Use a space character to indicate that negative numbers should be prefixed with a minus symbol and a leading space should be used for positive ones.

      '{: d}'.format((- 23))
      -23
      '{: d}'.format(42)
       42

       

      New style formatting is also able to control the position of the sign symbol relative to the padding.

      '{:=5d}'.format((- 23))
      -  23

       

      '{:=+5d}'.format(23)
      +  23

       

      data = {'nom': 'Mason', 'prenom': 'Nick'}
      '{nom} {prenom}'.format(**data)
      Mason Nick

       

      '{nom} {prenom}'.format(nom='Mason', prenom='Nick')
      Mason Nick

       

      qui = {'prenom': 'David', 'nom': 'Gilmour'}
      '{p[prenom]} {p[nom]}'.format(p=qui)
      David Gilmour

       

      data = [4, 8, 15, 16, 23, 42]
      '{d[4]} {d[5]}'.format(d=data)
      23 42

       

      class Plante(object):
          type = 'arbre'
      '{p.type}'.format(p=Plante())
      arbre

       

      class Plante(object):
          type = 'arbre'
          especes = [{'nom': 'chêne'}, {'nom': 'hêtre'}]
      '{p.type}: {p.especes[0][nom]}'.format(p=Plante())
      arbre: chêne

       

      from datetime import datetime
      '{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))
      2001-02-03 04:05

       

      '{:{align}{width}}'.format('test', align='^', width='10')
         test   

       

      '{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3)
      Gib = 2.718

       

      '{:{width}.{prec}f}'.format(2.7182, width=5, prec=2)
       2.72

       

      '{:{prec}} = {:{prec}}'.format('Gibberish', 2.7182, prec='.3')
      Gib = 2.72

       

      from datetime import datetime
      dt = datetime(2001, 2, 3, 4, 5)
      '{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')
      2001-02-03 04:05

       

      '{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)
           +2.72

       

      '{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')
           +2.72

       

      class HAL9000(object):
          def __format__(self, format):
              if (format == 'open-the-pod-bay-doors'):
                  return "I'm afraid I can't do that."
              return 'HAL 9000'
      
      '{:open-the-pod-bay-doors}'.format(HAL9000())
      I'm afraid I can't do that.

      Modulo Operator(%)

      The Modulo % operator can also be used for string formatting. It interprets the left argument much like a printf()-style format as in C language strings to be applied to the right argument. In Python, there is no printf() function but the functionality of the ancient printf is contained in Python. To this purpose, the modulo operator % is overloaded by the string class to perform string formatting. Therefore, it is often called a string modulo (or sometimes even called modulus) operator. The string modulo operator ( % ) is still available in Python(3.x) and is widely used. But nowadays the old style of formatting is removed from the language.

      # Python program showing how to use string modulo operator(%)

      print("Geeks : %2d, Portal : %5.2f" % (1, 05.333))

      print("Total students : %3d, Boys : %2d" % (240, 120)) # print integer value

      print("%7.3o" % (25)) # print octal value

      print("%10.3E" % (356.08977)) # print exponential value

      Output

      Geeks :  1, Portal : 5.33
      Total students : 240, Boys : 120
          031
      3.561E+02

      Formatting Output using String Modulo Operator(%) Output Formatting using Modulo Operator

      There are two of those in our example: “%2d” and “%5.2f”. The general syntax for a format placeholder is:

       %[flags][width][.precision]type

      Let’s take a look at the placeholders in our example.

      • The first placeholder ‘%2d’ is used for the first component of our tuple, i.e. the integer 1. It will be printed with 2 characters, and as 1 consists of only one digit, the output is padded with 1 leading blank.
      • The second placeholder ‘%5.2f’ is for a float number. Like other placeholders, it’s introduced with the % character. It specifies the total number of digits the string should contain, including the decimal point and all the digits, both before and after the decimal point.
      • Our float number 05.333 is formatted with 5 characters and a precision of 2, denoted by the number following the ‘.’ in the placeholder. The last character ‘f’ indicates that the placeholder represents a float value.

      Formatting Output using The Format Method

      The format() method was added in Python(2.6). The format method of strings requires more manual effort. Users use {} to mark where a variable will be substituted and can provide detailed formatting directives, but the user also needs to provide the information to be formatted. This method lets us concatenate elements within an output through positional formatting. For Example –

      Example 1: The code explain various Python string formatting techniques.The values are either explicitly supplied or referred to by the order in which they appear in the format() procedure.f-Strings enable the use of curly braces and the f prefix to embed expressions inside string literals. The f-Strings’ expressions are assessed and their appropriate values are substituted for them.

      print(‘I love {} for "{}!"‘.format(‘Geeks’, ‘Geeks’))

      # using format() method and referring a position of the object

      print(‘{0} and {1}’.format(‘Geeks’, ‘Portal’))

      print(‘{1} and {0}’.format(‘Geeks’, ‘Portal’))

      print(f"I love {‘Geeks’} for \"{‘Geeks’}!\"")

      # using format() method and referring a position of the object

      print(f"{‘Geeks’} and {‘Portal’}")

      Output

      I love Geeks for "Geeks!"
      Geeks and Portal
      Portal and Geeks
      I love Geeks for "Geeks!"
      Geeks and Portal

      The brackets and characters within them (called format fields) are replaced with the objects passed into the format() method. A number in the brackets can be used to refer to the position of the object passed into the format() method.

      Example 2:With the help of positional parameters and a named argument (‘other’) in the first line, the values ‘Geeks’, ‘For’, and ‘Geeks’ are added to the string template.’Geeks:12, Portal: 0.55′ is printed, with the first value appearing as a 2-digit integer and the second number having 2 decimal places and an 8-bit width. The format() method’s named arguments, denoted by specific labels (‘a’ and ‘p’) for the numbers ‘453’ and ‘59.058’,

      # combining positional and keyword arguments

      print(‘Number one portal is {0}, {1}, and {other}.’

      .format(‘Geeks’, ‘For’, other =’Geeks’))

      # using format() method with number

      print("Geeks :{0:2d}, Portal :{1:8.2f}".

      format(12, 00.546))

      # Changing positional argument

      print("Second argument: {1:3d}, first one: {0:7.2f}".

      format(47.42, 11))

      print("Geeks: {a:5d},  Portal: {p:8.2f}".

      format(a = 453, p = 59.058))

      Output

      Number one portal is Geeks, For, and Geeks.
      Geeks :12, Portal :    0.55
      Second argument:  11, first one:   47.42
      Geeks:   453, Portal:    59.06

      The following diagram with an example usage depicts how the format method works for positional parameters:

      Formatting Output using The Format Method Output Formatting using Format method

      Example 3:The code shows how to use dictionaries with Python’s format() method. The dictionary’s ‘tab’ in the first example has keys and associated values. The format() method uses indexing to put the values into the string template. In the second example, named keys in a dictionary are used as “data.

      tab = {‘geeks’: 4127, ‘for’: 4098, ‘geek’: 8637678}

      # using format() in dictionary

      print(‘Geeks: {0[geeks]:d}; For: {0[for]:d}; ‘

      ‘Geeks: {0[geek]:d}’.format(tab))

      data = dict(fun ="GeeksForGeeks", adj ="Portal")

      print("I love {fun} computer {adj}".format(**data))

      Output

      Geeks: 4127; For: 4098; Geeks: 8637678
      I love GeeksForGeeks computer Portal

      Formatting Output using The String Method

      This output is formatted by using string method i.e. slicing and concatenation operations. The string type has some methods that help in formatting output in a fancier way. Some methods which help in formatting an output are str.ljust(), str.rjust(), and str.centre()

      cstr = "I love geeksforgeeks"

      # Printing the center aligned string with fillchr

      print("Center aligned string with fillchr: ")

      print(cstr.center(40, ‘#’))

      # Printing the left aligned string with "-" padding

      print("The left aligned string is : ")

      print(cstr.ljust(40, ‘-’))

      # Printing the right aligned string with "-" padding

      print("The right aligned string is : ")

      print(cstr.rjust(40, ‘-’))

      Output

      Center aligned string with fillchr:
      ##########I love geeksforgeeks##########
      The left aligned string is :
      I love geeksforgeeks--------------------
      The right aligned string is :
      --------------------I love geeksforgeeks

      Python’s Format Conversion Rule

      This table lists the standard format conversion guidelines used by Python’s format() function.

      Conversion

      Meaning

      d

      Decimal integer

      b

      Binary format

      o

      octal format

      u

      Obsolete and equivalent to ‘d’

      x or X

      Hexadecimal format

      e or E

      Exponential notation

      f or F

      Floating-point decimal

      g or G

      General format

      c

      Single Character

      r

      String format(using repr())

      s

      String Format(using str()))

      %

      Percentage

       

      NOMBRE DE LIGNES ET COLONNES DANS UN TERMINAL

      import os
      rows, columns = os.popen('stty size', 'r').read().split()

       

 

Aucun commentaire

 

Laissez un commentaire