Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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.

like image 866
user664546 Avatar asked May 29 '11 17:05

user664546


People also ask

How do you split a string with a colon in Python?

Use the str. split() method to split a string on the colons, e.g. my_list = my_str. split(':') .

How do you split a string after a specific character in Python?

Python String | split()split() method in Python split a string into a list of strings after breaking the given string by the specified separator. Parameters : separator : This is a delimiter. The string splits at this specified separator.

How do you split the last part of a string in Python?

Use the str. rsplit() method with maxsplit set to 1 to split a string and get the last element. The rsplit() method splits from the right and will only perform a single split when maxsplit is set to 1 .

How do you get text after a character in Python?

In Python, the str[0:n] option extracts a substring from a string. We may need to acquire the string that occurs after the substring has been found in addition to finding the substring.


2 Answers

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] 
like image 109
sorin Avatar answered Oct 02 '22 15:10

sorin


foo = "client:user:username:type:1234567" last = foo.split(':')[-1] 
like image 30
ralphtheninja Avatar answered Oct 02 '22 16:10

ralphtheninja