Extract last two fields from split

I want to extract the last two field values ​​from a variable variable length. For example, consider the three values ​​below:

fe80::e590:1001:7d11:1c7e ff02::1:ff1f:fb6 fe80::7cbe:e61:f5ab:e62 ff02::1:ff1f:fb6 

These three lines are of variable length. I want to extract only the last two field values ​​if I split each row into a separator:

That is, from three lines I want:

 7d11, 1c7e ff1f, fb6 ff1f, fb6 

Can this be done with split() ? I have no ideas.

+7
source share
2 answers

If s is a string containing an IPv6 address, use

 s.split(":")[-2:] 

to get the last two components. The split() method returns a list of all components, and [-2:] will truncate this list to return only the last two items.

+16
source

You can use str.rsplit() to split right:

 >>> ipaddress = 'fe80::e590:1001:7d11:1c7e' >>> ipaddress.rsplit(':', 2) # splits at most 2 times from the right ['fe80::e590:1001', '7d11', '1c7e'] 

This avoids unnecessary separation of the first part of the address.

+15
source

All Articles