I have to get all the values before the last colon(:) i.e. client:user:username:type
from the following string:
Input: client:user:username:type:1234567
Output: client:user:username:type
I know I can split by :
and then iterate and append all the tokens before :
.
But is there a better pythonic way to achieve this?
Advertisement
Answer
just find the index of last :
and then extract the rest of string base on that
string="client:user:username:type:1234567" index = string[::-1].index(':') new_string = string[:len(string)-index-1] print(new_string)
output
client:user:username:type
as suggested by @muzzletov, you can use str.rindex
and then do string slicing
new_string = string[:string.rindex(':')]