Python 字符串 rpartition() 方法
描述
rpartition() 方法与 partition() 方法类似,不同之处在于字符串在分隔符字符串的最后一次出现处被分割。
语法
var.rpartition(sep)
参数
- sep − 用于分隔的字符串
返回值
该方法返回一个由三个字符串组成的元组。
示例
var = 'Explicit is better than implicit'
var1 = var.rpartition('ci')
print ("原始字符串:", var)
print ("分割结果:", var1)
var = "Explicit is better than implicit"
var2 = var.rpartition('IS')
print ("原始字符串:", var)
print ("分割结果:", var2)
var = 'Explicit is better than implicit'
var3 = var.rpartition("")
print ("原始字符串:", var)
print ("分割结果:", var3)
运行此程序时,会产生以下输出 −
原始字符串: Explicit is better than implicit
分割结果: ('Explicit is better than impli', 'ci', 't')
原始字符串: Explicit is better than implicit
分割结果: ('', '', 'Explicit is better than implicit')
Traceback (most recent call last):
File "C:\Users\mlath\examples\main.py", line 12, in <module>
var3 = var.rpartition("")
^^^^^^^^^^^^^^^^^^
ValueError: empty separator