Python String split ()

La méthode split () rompt une chaîne au séparateur spécifié et renvoie une liste de chaînes.

La syntaxe de split()est:

 str.split ((séparateur (, maxsplit)))

Paramètres split ()

split() La méthode prend au maximum 2 paramètres:

  • séparateur (facultatif) - C'est un délimiteur. La chaîne se divise au niveau du séparateur spécifié.
    Si le séparateur n'est pas spécifié, toute chaîne d'espaces blancs (espace, nouvelle ligne, etc.) est un séparateur.
  • maxsplit (facultatif) - Le maxsplit définit le nombre maximal de fractionnements.
    La valeur par défaut de maxsplit est -1, ce qui signifie qu'il n'y a pas de limite sur le nombre de divisions.

Valeur de retour de split ()

split() rompt la chaîne au niveau du séparateur et renvoie une liste de chaînes.

Exemple 1: Comment fonctionne split () en Python?

 text= 'Love thy neighbor' # splits at space print(text.split()) grocery = 'Milk, Chicken, Bread' # splits at ',' print(grocery.split(', ')) # Splitting at ':' print(grocery.split(':'))

Production

 ('Amour', 'ton', 'voisin') ('Lait', 'Poulet', 'Pain') ('Lait, Poulet, Pain')

Exemple 2: Comment fonctionne split () lorsque maxsplit est spécifié?

 grocery = 'Milk, Chicken, Bread, Butter' # maxsplit: 2 print(grocery.split(', ', 2)) # maxsplit: 1 print(grocery.split(', ', 1)) # maxsplit: 5 print(grocery.split(', ', 5)) # maxsplit: 0 print(grocery.split(', ', 0))

Production

 ('Lait', 'Poulet', 'Pain, Beurre') ('Lait', 'Poulet, Pain, Beurre') ('Lait', 'Poulet', 'Pain', 'Beurre') ('Lait, Poulet') , Pain au beurre')

Si maxsplit est spécifié, la liste contiendra le maximum d' maxsplit+1éléments.

Articles intéressants...