Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract last two fields from split

Tags:

python

I want to extract last two field values from a variable of varying 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 lengths. I want to extract only the last two field values if i split each line by delimiter :

That is, from the three lines, i want:

7d11, 1c7e

ff1f, fb6

ff1f, fb6

Can this be done using split()? I am not getting any ideas.

like image 922
learner Avatar asked May 31 '12 16:05

learner


People also ask

How do you get the last split element?

To split a string and get the last element of the array, call the split() method on the string, passing it the separator as a parameter, and then call the pop() method on the array, e.g. str. split(','). pop() . The pop() method will return the last element from the split string array.

What does the split () method return from a list of words?

Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.

Does the split function return a list?

The Split function returns a list of words after separating the string or line with the help of a delimiter string such as the comma ( , ) character.

How do you split text in bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.


2 Answers

If s is the string containing the IPv6 address, use

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

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

like image 109
Sven Marnach Avatar answered Oct 07 '22 11:10

Sven Marnach


You can use str.rsplit() to split from the 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 the unnecessary splitting of the first part of the address.

like image 45
Matt Avatar answered Oct 07 '22 10:10

Matt