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.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
user664546
  • 4,891
  • 4
  • 22
  • 19

3 Answers3

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]
sorin
  • 161,544
  • 178
  • 535
  • 806
  • 1
    Anyone has checked speed/memory difference between the two methods? – EndermanAPM Sep 30 '20 at 06:30
  • "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`). – mirekphd Oct 10 '20 at 12:17
  • 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](https://stackoverflow.com/questions/6903557) which includes timing results. – Karl Knechtel Jan 22 '23 at 13:06
31
foo = "client:user:username:type:1234567"
last = foo.split(':')[-1]
rtn
  • 127,556
  • 20
  • 111
  • 121
18

Use this:

"client:user:username:type:1234567".split(":")[-1]
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • 10
    Alternatively, .rsplit(":", 1)[-1], which splits at most once (from the right-hand end). – MRAB May 29 '11 at 19:55