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
JavaScript
x
5
1
string="client:user:username:type:1234567"
2
index = string[::-1].index(':')
3
new_string = string[:len(string)-index-1]
4
print(new_string)
5
output
JavaScript
1
2
1
client:user:username:type
2
as suggested by @muzzletov, you can use str.rindex
and then do string slicing
JavaScript
1
2
1
new_string = string[:string.rindex(':')]
2