python中的分区字符串,获取冒号后的最后一段的值

use*_*546 32 python string

我需要在此示例1234567中的最后一个冒号后获取值

client:user:username:type:1234567
Run Code Online (Sandbox Code Playgroud)

我不需要字符串中的任何其他内容只是最后一个id值.

sor*_*rin 61

result = mystring.rpartition(':')[2]
Run Code Online (Sandbox Code Playgroud)

如果string没有:,则结果将包含原始字符串.

一个应该慢一点的替代方案是:

result = mystring.split(':')[-1]
Run Code Online (Sandbox Code Playgroud)


ral*_*nja 28

foo = "client:user:username:type:1234567"
last = foo.split(':')[-1]
Run Code Online (Sandbox Code Playgroud)


Bjö*_*lex 16

用这个:

"client:user:username:type:1234567".split(":")[-1]
Run Code Online (Sandbox Code Playgroud)

  • 或者,.rsplit(":",1)[ - 1],最多分裂一次(从右端). (9认同)