extract last two fields from split

前端 未结 2 738
悲&欢浪女
悲&欢浪女 2021-01-04 06:10

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:f         


        
相关标签:
2条回答
  • 2021-01-04 06:45

    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.

    0 讨论(0)
  • 2021-01-04 06:49

    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.

    0 讨论(0)
提交回复
热议问题