Skip to article frontmatterSkip to article content

formatage des chaînes : f-strings

pour le formatage des chaines: utilisez les f-strings, qui évitent les répétitions fastidieuses
l’idée consiste à

import math
nom, age = "Pierre", 42
f"{nom} a {age} ans"
'Pierre a 42 ans'
f"360° = {2*math.pi} radians"
'360° = 6.283185307179586 radians'

f-string : expression et format

print(f"ᴨ arrondi à deux décimales = {math.pi:.2f}")
ᴨ arrondi à deux décimales = 3.14

= dans une f-string

grâce au = optionnel, on peut obtenir en une seule fois un double affichage:

# et c'est très pratique pour le debugging
def add(x, y):
    return x+y

a, b = 10, 30

# c'est ici:      ⬇
print(f"{add(a, b)=}")
add(a, b)=40

formats - scientifiques

formats scientifiques usuels: e f et g, cf. printf

x = 23451.23423536563
f'{x:e} | {x:f} | {x:g} | {x:010.1f} | {x:.2f}'
'2.345123e+04 | 23451.234235 | 23451.2 | 00023451.2 | 23451.23'
y = 769876.11434
f'{x:e} | {y:f} | {x:g} | {y:010.2f} | {x:.2f}'
'2.345123e+04 | 769876.114340 | 23451.2 | 0769876.11 | 23451.23'

Voir aussi pour plus de détails:
https://mkaz.blog/code/python-string-format-cookbook/

justification

pour faire de la justification, on dispose des formats < ˆ et >

f"|{nom:<12}|{nom:^12}|{nom:>12}|"
'|Pierre | Pierre | Pierre|'
# on peut aussi préciser avec quel caractère remplir
num = 123
f"|{num:<12}|{num:-^12}|{num:0>12}|"
'|123 |----123-----|000000000123|'

expression dans le format

un peu plus avancé, mais notez qu’on peut également utiliser des expressions dans le format

from decimal import Decimal
value = Decimal('12.34567')
# ici la précision de 4
# signifie 4 chiffres
# significatifs en tout

f"value = >{value:10.4}<"
'value = > 12.35<'
# si nécessaire la précision 
# peut aussi être un paramètre !

width = 10
precision = 4
f"value = >{value:{width}.{precision}}<"
'value = > 12.35<'

affichage avec print()

print(obj1, .., objn, sep=' ', end='\n',
      file=sys.stdout, flush=False)

enlever le newline

for i in range(10):
    print(i, end='')
0123456789

redirection dans un fichier

with open('test.txt', 'w') as channel:
    L = list(range(10))
    for item in L:
        print(item, file=channel, end=' + ')
    print("\n", file=channel)

plusieurs paramètres

print(1, 'x', True)
1 x True
print(1, 'x', True, sep='_')
1_x_True
# dans un notebook ce n'est pas très parlant
# mais ici on n'obtiendrait PAS de retour à la ligne
print(1, 'x', True, sep='_', end='FIN')
1_x_TrueFIN
# et ici on en obtiendrait deux (soit une ligne blanche)
print(1, 'x', True, sep='_', end='\n\n')
1_x_True

module logging (avancé)

c’est la bonne façon de conserver des traces d’exécutionpour un programme en production

formatage : méthodes old-school

formatage avec str.format() (old-school)

# anonyme (dans l'ordre)
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
# par index
print('{1} and {0} {0}'.format('spam', 'eggs'))
eggs and spam spam
# par nom
print('This {food} is {adjective}'
      .format(food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible

formatage avec % (very old-school)

nom = "Alice"
"%s dit bonjour" % nom
'Alice dit bonjour'
d = 3
"%i + %i = %i" % (d, d, d + d)
'3 + 3 = 6'
"%(food)s is %(adjective)s" % {'food' : 'bacon',
                               'adjective' : 'delicious' }
'bacon is delicious'

attention avec +

'abc' + 'def'
'abcdef'
age = 35
try: 'alice a ' + age + ' ans'
except Exception as e: print ("OOPS", e)
OOPS can only concatenate str (not "int") to str
'alice a ' + str(age) + ' ans'
'alice a 35 ans'