Pour formater l'affichage la vieille méthode utilisant %
est remplacée par la méthode .format()
. Le but de cet article est de faciliter le passage de l'ancienne méthode à la nouvelle.
Source : PyFormat
Méthode % : '%s %2.1f' % ('python', 3.5)
#2 chiffres, 1 décimale
Méthode .format() : '{} {:2.1f}'.format('python', 3.5)
Résultat : python 3.5
On peut faire appels aux conversions avec str()
ou avec repr
.
Méthode % : '%s' % ("python")
; '%r' % ("python")
Méthode .format() ; '{!s}'.format("python")
; '{!r}'.format("python")
Résultat : 'python' ; "'python'"
Note: str
est la conversion pour l'affichage usuel, alors que repr
est la conversion pour l'affichage à l'usage du programmeur.
Méthode % : '%8s' % ('python')
Méthode .format() : '{:>8}'.format('python')
Résultat : python
Méthode % : '%-8s' % ('python')
Méthode .format() : '{:8}'.format('python')
Résultat : python
Méthode .format() : '{:*>8}'.format('python')
Résultat : **python
Méthode .format() : '{:^8}'.format('python')
Résultat : python
Méthode % : '%.3s' %('mercredi')
Méthode .format() : '{:.3}'.format('mercredi')
Résultat : mer
Méthode % : '%-6.3s' % ('mercredi')
Méthode .format() : '{:6.3}'.format('mercredi')
Résultat : mer '%-6.3s' % ('mercredi');
Méthode % : '%d' % (27, )
# marche avec 27.2
Méthode .format() : '{:d}'.format(27,)
# ne marche qu'avec des entiers
Résultat : 27
Méthode % : '%.2f' % (2.71828)
Méthode .format() : '{:.2f}'.format(2.71828)
Résultat : 2.72 Le résultat est arrondi au plus près
C'est comme avec le texte.
Méthode % : '%02d/%02d' % (2,9)
Méthode .format() : '{:02d}/{:02d}'.format(2, 9)
Résultat : 02/09
Par défaut seul le signe - est mis.
Méthode % : '%+d°' % (19,)
Méthode .format() : '{:+d}°'.format(19)
Résultat : +19°
Le signe peut être placé au début du remplissage.
Méthode .format() : '{:=+3d} ; {:=+3d}'.format(7,-2)
Résultat : + 7 ; - 2 le signe compte pour un emplacement
Avec le code suivant :
from datetime import datetime
d = '{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))
print(d)
Résultat : 2001-02-03 04:05
week = ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche']
print('ouvert {w[2]} et {w[5]}'.format(w=week))
Résultat :
On peut même paramétrer le formatage. Exemple :
Code : '{:{align}{width}}'.format('test', align='^', width='10')
Résultat : test
Méthode % : '%.*s = %.*f' % (3, 'charabia', 3, 2.71828)
Méthode .format() : '{:.{pr}} = {:.{pr}f}'.format('charabia', 2.71828, pr=3)
Résultat : cha = 2.718