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

Utilisation et exemple de rsplit() pour les chaînes de caractères Python

Python string methods

La méthode rsplit() coupe la chaîne de caractères à partir de la droite à l'endroit spécifié par le séparateur, et retourne une liste de chaînes.

La syntaxe de rsplit() est :

str.rsplit([separator, maxsplit])

Paramètres de rsplit()

Le méthode rsplit() peut accepter au plus2Un paramètre :

  • separator(Optionnel)-C'est un séparateur. L'objectif de la méthode est : couper la chaîne de caractères à partir de la droite à l'endroit spécifié par le séparateur.

  • Si separator n'est pas spécifié, tout espace (espace, retour chariot, etc.) est un séparateur.

  • maxsplit(Optionnel)- maxsplit définit le nombre maximum de coupes.
    La valeur par défaut est maxsplit-1, indicating that the split count is unlimited.

rsplit() return value

The rsplit() method splits the string into a list starting from the right.
If 'maxsplit' is not specified, this method will return the same result as the split() method.
Note: If maxsplit is specified, the list will contain one more element than the specified number.

Example1How does rsplit() work in Python?

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

When running the program, the output is:

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

If maxsplit is not specified, the behavior of rsplit() is similar to split().

Example2How does split() work when maxsplit is specified?

grocery = 'Milk, Chicken, Bread, Butter'
# maxsplit: 2
print(grocery.rsplit(', ')) 2))
# maxsplit: 1
print(grocery.rsplit(', ')) 1))
# maxsplit: 5
print(grocery.rsplit(', ')) 5))
# maxsplit: 0
print(grocery.rsplit(', ', 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