partition string in python and get value of last segment after colon

Question:

I need to get the value after the last colon in this example 1234567

client:user:username:type:1234567

I don’t need anything else from the string just the last id value.


To split on the first occurrence instead, see Splitting on first occurrence.

Asked By: user664546

||

Answers:

Use this:

"client:user:username:type:1234567".split(":")[-1]
Answered By: Björn Pollex
foo = "client:user:username:type:1234567"
last = foo.split(':')[-1]
Answered By: ralphtheninja
result = mystring.rpartition(':')[2]

If you string does not have any :, the result will contain the original string.

An alternative that is supposed to be a little bit slower is:

result = mystring.split(':')[-1]
Answered By: sorin

You could also use pygrok.

from pygrok import Grok
text = "client:user:username:type:1234567"
pattern = """%{BASE10NUM:type}"""
grok = Grok(pattern)
print(grok.match(text))

returns

{'type': '1234567'}
Answered By: bwl1289
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.