分割python中的字符串,得到冒号前的所有值

Partition string in python and get all the value before colon

我必须获取最后一个冒号 (:) 之前的所有值,即来自以下字符串的 client:user:username:type

输入:client:user:username:type:1234567 输出:client:user:username:type

我知道我可以按 : 拆分,然后迭代并附加 : 之前的所有标记。

但是有更好的 pythonic 方法来实现这个吗?

只需找到最后一个 : 的索引,然后在此基础上提取其余字符串

string="client:user:username:type:1234567"
index = string[::-1].index(':')
new_string = string[:len(string)-index-1]
print(new_string)

输出

client:user:username:type

按照@muzzletov 的建议,您可以使用str.rindex 然后进行字符串切片

 new_string = string[:string.rindex(':')]