English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Méthode d'utilisation et exemples de str.split() en Python

Python string methods

La méthode split() décompose une chaîne de caractères à l'endroit du séparateur spécifié et retourne une liste de chaînes de caractères.

La syntaxe de split() est :

str.split([separator, [maxsplit]])

paramètre split()

La méthode split() peut utiliser au maximum2un paramètre :

  • separator(Optional)-Is a separator. The string is split at the specified separator (separator). 
    If the separator is not specified, any whitespace (spaces, newline characters, etc.) is a separator.

  • maxsplit(Optional)- maxsplit defines the maximum number of splits.
    The default value is maxsplit-1, indicating that the split count is unlimited.

split() return value

split() splits the string at the separator and returns a list of strings.

Example1How does split() work in Python?

text = 'Love thy neighbor'
# Split at spaces
print(text.split())
grocery = 'Milk, Chicken, Bread'
# Split at ','
print(grocery.split(', '))
# Split at ':'
print(grocery.split(':'))

When running the program, the output is:

['Love', 'thy', 'neighbor']
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']

Example2How does split() work when maxsplit is specified?

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))

When running the program, the output is:

['Milk', 'Chicken, Bread, Butter']
['Milk', 'Chicken, Bread, Butter']
['Milk', 'Chicken', 'Bread', 'Butter']
['Milk, Chicken, Bread, Butter']

If maxsplit is specified, the list will contain at most maxsplit+1Project.

Python string methods