1. A propos de la méthode isidentifier()
La méthode isidentifier() vérifie si une chaîne peut être utilisée comme identifiant valide en Python (nom de variable, fonction, classe). Elle suit les règles de nommage du langage.
|
1 2 |
# Syntaxe chaine.isidentifier() |
|
1 2 3 4 5 6 |
# Exemples simples print("variable".isidentifier()) # True print("ma_variable".isidentifier()) # True print("123variable".isidentifier()) # False (commence par chiffre) print("var-test".isidentifier()) # False (contient -) print("".isidentifier()) # False (vide) |
|
1 2 3 4 5 6 |
# Output: # True # True # False # False # False |
2. Règles de validation
2.1 Caractères autorisés
Un identifiant valide doit respecter ces règles :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
tests = [ ("var", True), # Lettres seulement ("VAR", True), # Majuscules ("_var", True), # Commence par _ ("var123", True), # Chiffres après première lettre ("123var", False), # Ne commence pas par chiffre ("var-test", False), # Pas de tiret ("var.test", False), # Pas de point ("var test", False), # Pas d'espace ("for", True), # Mot-clé (valide syntaxiquement) ("", False) # Pas vide ] print("Règles des identifiants:") for texte, attendu in tests: resultat = texte.isidentifier() ok = "✓" if resultat == attendu else "✗" print(f"{ok} '{texte:10}' -> {resultat:5} (attendu: {attendu})") |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
# Output: # Règles des identifiants: # ✓ 'var ' -> True (attendu: True) # ✓ 'VAR ' -> True (attendu: True) # ✓ '_var ' -> True (attendu: True) # ✓ 'var123 ' -> True (attendu: True) # ✓ '123var ' -> False (attendu: False) # ✓ 'var-test ' -> False (attendu: False) # ✓ 'var.test ' -> False (attendu: False) # ✓ 'var test ' -> False (attendu: False) # ✓ 'for ' -> True (attendu: True) # ✓ ' ' -> False (attendu: False) |
2.2 Différence avec les mots-clés
isidentifier() ne vérifie pas si c'est un mot-clé réservé :
|
1 2 3 4 5 6 7 8 9 |
import keyword mots = ["if", "else", "def", "class", "ma_var", "print"] print("Vérification identifiants vs mots-clés:") for mot in mots: est_identifiant = mot.isidentifier() est_mot_cle = keyword.iskeyword(mot) print(f"'{mot:10}' -> identifiant: {est_identifiant:5}, mot-clé: {est_mot_cle}") |
|
1 2 3 4 5 6 7 8 |
# Output: # Vérification identifiants vs mots-clés: # 'if ' -> identifiant: True , mot-clé: True # 'else ' -> identifiant: True , mot-clé: True # 'def ' -> identifiant: True , mot-clé: True # 'class ' -> identifiant: True , mot-clé: True # 'ma_var ' -> identifiant: True , mot-clé: False # 'print ' -> identifiant: True , mot-clé: False |
3. Applications pratiques
3.1 Validation de noms de variables
Validation complète incluant la vérification des mots-clés :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def valider_nom_variable(nom): if not nom or not nom.isidentifier(): return f"'{nom}' n'est pas un identifiant valide" import keyword if keyword.iskeyword(nom): return f"'{nom}' est un mot-clé réservé" return f"'{nom}' est un nom valide" # Tests noms = ["ma_var", "123var", "if", "nom_valide", "var-test", ""] for nom in noms: print(f"{nom:15} -> {valider_nom_variable(nom)}") |
|
1 2 3 4 5 6 7 |
# Output: # ma_var -> 'ma_var' est un nom valide # 123var -> '123var' n'est pas un identifiant valide # if -> 'if' est un mot-clé réservé # nom_valide -> 'nom_valide' est un nom valide # var-test -> 'var-test' n'est pas un identifiant valide # -> '' n'est pas un identifiant valide |
3.2 Nettoyage de chaînes pour identifiants
Convertir une chaîne arbitraire en identifiant valide :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
def nettoyer_identifiant(texte): if not texte: return "_vide" # Remplacer caractères non valides ident = "" for i, c in enumerate(texte): if i == 0 and not (c.isalpha() or c == '_'): ident += '_' elif c.isalnum() or c == '_': ident += c else: ident += '_' # Simplifier les underscores import re ident = re.sub('_+', '_', ident).strip('_') return ident if ident else "_" # Exemples tests = ["Nom Variable", "123test", "email@site.com", "âge"] for t in tests: result = nettoyer_identifiant(t) valide = result.isidentifier() print(f"'{t:20}' -> '{result}' (valide: {valide})") |
|
1 2 3 4 5 |
# Output: # 'Nom Variable ' -> 'Nom_Variable' (valide: True) # '123test ' -> '_123test' (valide: True) # 'email@site.com ' -> 'email_site_com' (valide: True) # 'âge ' -> '_âge' (valide: False) |
3.3 Filtrage d'identifiants dans du texte
Extraire les identifiants valides d'un texte :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def extraire_identifiants(texte): import re mots = re.findall(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b', texte) return [mot for mot in mots if mot.isidentifier()] code = """ def calculer(x, y): resultat = x + y return resultat total = calculer(10, 20) print(total) """ identifiants = extraire_identifiants(code) print("Identifiants trouvés:") for i, ident in enumerate(identifiants, 1): print(f" {i:2}. {ident}") print(f"\nTotal: {len(identifiants)} identifiants") |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Output: # Identifiants trouvés: # 1. def # 2. calculer # 3. x # 4. y # 5. resultat # 6. x # 7. y # 8. resultat # 9. total # 10. calculer # 11. print # 12. total # # Total: 12 identifiants |
Auteur : Younes Derfoufi
Lieu de travail : CRMEF OUJDA
Site Web : www.tresfacile.net
Chaine YouTube : https://www.youtube.com/user/InformatiquesFacile
Me contacter : https://www.tresfacile.net/me-contacter/



