rsplit()方法在從右側將指定的字符串分隔指定的分隔符後,返回字符串列表。
用法:
str.rsplit(separator, maxsplit)
參數:
- separator:是分隔符。字符串從右側開始在此指定的分隔符處分割。如果未提供,則任何空格都是分隔符。
- maxsplit:它是一個數字,它告訴我們將字符串分成提供的最大次數。如果未提供,則沒有限製。
返回:
在指定的分隔符從右側斷開給定字符串後,返回字符串列表。
錯誤:
We will not get any error even if we are not passing any argument.
代碼#1
# Python code to split a string
# using rsplit.
# Splits at space
word = 'geeks for geeks'
print(word.rsplit())
# Splits at 'g'. Note that we have
# provided maximum limit as 1. So
# from right, one splitting happens
# and we get "eeks" and "geeks, for, "
word = 'geeks, for, geeks'
print(word.rsplit('g', 1))
# Splitting at '@' with maximum splitting
# as 1
word = 'geeks@for@geeks'
print(word.rsplit('@', 1))
輸出:
['geeks', 'for', 'geeks'] ['geeks, for, ', 'eeks'] ['geeks@for', 'geeks']
代碼#2
word = 'geeks, for, geeks, pawan'
# maxsplit:0
print(word.rsplit(', ', 0))
# maxsplit:4
print(word.rsplit(', ', 4))
word = 'geeks@for@geeks@for@geeks'
# maxsplit:1
print(word.rsplit('@', 1))
# maxsplit:2
print(word.rsplit('@', 2))
輸出:
['geeks, for, geeks, pawan'] ['geeks', 'for', 'geeks', 'pawan'] ['geeks@for@geeks@for', 'geeks'] ['geeks@for@geeks', 'for', 'geeks']
代碼#3
word = 'geeks for geeks'
# Since seperator is 'None',
# so, will be splitted at space
print(word.rsplit(None, 1))
print(word.rsplit(None, 2))
# Also observe these
print('@@@@@geeks@for@geeks'.rsplit('@'))
print('@@@@@geeks@for@geeks'.rsplit('@', 1))
print('@@@@@geeks@for@geeks'.rsplit('@', 3))
print('@@@@@geeks@for@geeks'.rsplit('@', 5))
輸出:
['geeks for', 'geeks'] ['geeks', 'for', 'geeks'] ['', '', '', '', '', 'geeks', 'for', 'geeks'] ['@@@@@geeks@for', 'geeks'] ['@@@@', 'geeks', 'for', 'geeks'] ['@@', '', '', 'geeks', 'for', 'geeks']
相關用法
注:本文由純淨天空篩選整理自pawan_asipu大神的英文原創作品 Python String | rsplit()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。