Python propose plusieurs fonctions natives pour convertir des nombres entre différentes bases.
Binaire
La fonction bin() convertit un entier décimal en représentation binaire :
>>> valeur = 10
>>> bin(valeur)
'0b1010'
Octal
>>> nombre = 9
>>> oct(nombre)
'0o11'
Hexadécimal
>>> chiffre = 15
>>> hex(chiffre)
'0xf'
Conversion entre types de données
Chaîne vers octets
>>> texte = "pomme"
>>> bytes(texte, encoding='utf-8')
b'pomme'
Vers chaîne de caractères
>>> entier = 100
>>> str(entier)
'100'
Entier vers caractère ASCII
>>> chr(65)
'A'
Caractère ASCII vers entier
>> caractere = 'A'
>>> ord(caractere)
65
Construction de dictionnaires
>>> dict()
{}
>>> dict(x='x', y='y')
{'x': 'x', 'y': 'y'}
>>> dict(zip(['x', 'y'], [1, 2]))
{'x': 1, 'y': 2}
>>> dict([('x', 1), ('y', 2)])
{'x': 1, 'y': 2}
Vers flottant
>>> float(3)
3.0
>>> float('abc')
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
float('abc')
ValueError: could not convert string to float: 'abc'
</module></pyshell>
Vers entier
La fonction int() accepte un second paramètre pour spécifier la base :
>>> int('12', 16)
18
Vers ensemble
>>> elements = [1, 4, 2, 3, 1]
>>> set(elements)
{1, 2, 3, 4}
Vers tranche (slice)
>>> donnees = [1, 4, 2, 3, 1]
>>> ma_tranche = slice(0, 5, 2)
>>> donnees[ma_tranche]
[1, 2, 1]
Vers tuple
>>> seq = [1, 3, 5]
>>> seq.append(7)
>>> seq
[1, 3, 5, 7]
>>> immutable = tuple(seq)
>>> immutable
(1, 3, 5, 7)
Vers frozenset
>>> ensemble_glace = frozenset([1, 1, 3, 2, 3])
>>> ensemble_glace
frozenset({1, 2, 3})
Opérations mathématiques
Quotient et reste
>>> divmod(10, 3)
(3, 1)
Puissance et modulo
>>> pow(3, 2, 4)
1
Arrondi
>>> round(10.045, 2)
10.04
>>> round(10.046, 2)
10.05
Taille mémoire d'un objet
>>> import sys
>>> d = {'a': 1, 'b': 2.0}
>>> sys.getsizeof(d)
240
Fonctions utilitaires
Évaluation d'expressions
>>> eval('3 + 5 * 2')
13
Vérification de vérité
>>> all([True, False, True])
False
>>> any([True, False, True])
True
Saisie utilisateur
>>> saisie = input("Entrez une valeur : ")
Formatage de chaînes
>>> nom = "Python"
>>> version = 3.12
>>> f"Langage : {nom}, Version : {version}"
'Langage : Python, Version : 3.12'
Hachage d'objet
>>> hash(42)
42
>>> hash("test")
Ouverture de fichiers
>>> fichier = open('donnees.txt', 'r', encoding='utf-8')
Type d'objet
>>> type(42)
<class>
>>> type("hello")
<class>
</class></class>
Inspection d'objets
Création de propriétés
class Cercle:
def __init__(self, rayon):
self._rayon = rayon
@property
def rayon(self):
return self._rayon
@rayon.setter
def rayon(self, valeur):
if valeur > 0:
self._rayon = valeur
Appelabilité
>>> class Etudiant:
... def __call__(self):
... return "Je suis callable"
...
>>> etudiant = Etudiant()
>>> callable(etudiant)
True
Suppression dynamique d'attribut
>>> class Personne:
... nom = "Alice"
...
>>> delattr(Personne, 'nom')
Récupération d'attribut
>>> class Personne:
... nom = "Alice"
...
>>> getattr(Personne, 'nom')
'Alice'
Vérification d'attribut
>>> hasattr(Personne, 'nom')
True
Vérification de type
>>> isinstance(42, int)
True
>>> isinstance(42, (int, float))
True
Hiérarchie de classes
>>> class Parent:
... pass
...
>>> class Enfant(Parent):
... pass
...
>>> issubclass(Enfant, Parent)
True
Liste des attributs
>>> dir(str)
['__add__', '__contains__', '__eq__', ...]
Itération et filtrage
Énumération
>>> couleurs = ['rouge', 'vert', 'bleu']
>>> list(enumerate(couleurs))
[(0, 'rouge'), (1, 'vert'), (2, 'bleu')]
Itérateur de plage
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(2, 8, 2))
[2, 4, 6]
Inversion
>>> liste = [1, 2, 3]
>>> list(reversed(liste))
[3, 2, 1]
Compression d'itérables
>> noms = ['Alice', 'Bob']
>>> ages = [25, 30]
>>> list(zip(noms, ages))
[('Alice', 25), ('Bob', 30)]
Filtrage
>>> nombres = [1, 2, 3, 4, 5, 6]
>>> list(filter(lambda n: n % 2 == 0, nombres))
[2, 4, 6]
Traietment de chaînes
Comparaison chaînée
>>> x = 5
>>> 1 < x < 10
True
Découpage avec split
>>> phrase = "un,deux,trois"
>>> phrase.split(',')
['un', 'deux', 'trois']
Remplacement avec replace
>>> texte = "bonjour monde"
>>> texte.replace('monde', 'Python')
'bonjour Python'
Traitement de fichiers CSV simplifié
fichier_source = open('donnees.csv', 'r', encoding='utf-8')
fichier_sortie = open('resultat.csv', 'w')
for ligne in fichier_source.readlines():
champs = ligne.strip('\n').split(',')
if champs[1] == 'earpa001':
fichier_sortie.write('{},{},{},{}\n'.format(
champs[0], champs[1], champs[2], champs[3]
))
fichier_source.close()
fichier_sortie.close()