Langage Python

L'essentiel du langage Python: syntaxe, fonctions et exemples

print()
Fonction d'affichage standard
Python
print("Hello, World!")
f-strings
Chaînes de caractères formatées (Python 3.6+)
Python
name = "John"
age = 30
print(f"Hello, {name}! You are {age} years old.")
str.format()
Méthode de formatage de chaînes
Python
name = "John"
age = 30
print("Hello, {}! You are {} years old.".format(name, age))
% operator
Opérateur de formatage (style C)
Python
name = "John"
age = 30
print("Hello, %s! You are %d years old." % (name, age))
{:d}
Format entier
Python
num = 42
print(f"Nombre: {num:d}")
{:f}
Format nombre à virgule flottante
Python
pi = 3.14159
print(f"Pi: {pi:f}")
{:.2f}
Format nombre à virgule flottante avec précision
Python
pi = 3.14159
print(f"Pi: {pi:.2f}")
{:,}
Format nombre avec séparateur de milliers
Python
num = 1000000
print(f"Nombre: {num:,}")
{:e}
Format notation scientifique
Python
num = 1000000
print(f"Nombre: {num:e}")
{:%}
Format pourcentage
Python
ratio = 0.25
print(f"Pourcentage: {ratio:%}")
{:b}
Format binaire
Python
num = 42
print(f"Binaire: {num:b}")
{:x}
Format hexadécimal
Python
num = 42
print(f"Hexadécimal: {num:x}")
{:o}
Format octal
Python
num = 42
print(f"Octal: {num:o}")