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.
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With