51

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.

3 Answers 3

103
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]
Sign up to request clarification or add additional context in comments.

3 Comments

Anyone has checked speed/memory difference between the two methods?
"Slower" for script languages means: "slower to type or recall":) So I think the order of the methods should be reversed (but +1 for the .split).
The .split approach is slower because it must make multiple splits and because it is not optimized for the specific case of looking for only one split. To perform only one split would require something like s.rsplit(':', 1)[-1], but this is still around 36% slower than using .rpartition. We're talking about nanoseconds, though. I have an answer on the related question Splitting on first occurrence which includes timing results.
31
foo = "client:user:username:type:1234567"
last = foo.split(':')[-1]

Comments

18

Use this:

"client:user:username:type:1234567".split(":")[-1]

1 Comment

Alternatively, .rsplit(":", 1)[-1], which splits at most once (from the right-hand end).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.