简体   繁体   中英

Split and take n words from the end

How would you take the last n end words from a split line? For example I have these lines:

1. 123.by2.gateway.edge.messenger.live.com
2. messenger.com
3. 10.17.123.45
4. 126.by2.gateway.edge.messenger.live.com
5. 14.messenger.live.com

I want to take the 3 last words from the addresses so that for lines 1, 4 & 5 I have 'messenger.live.com' and lines 2 & 3 remain intact. This is what I have done to achieve it, but seems to be lame:

link = line.split('.') 
if len(link) > 4: # to bypass the IP address
    plink = link[-1:-3] ?

You want to take

plink = link[-3:]

To ignore the numeric IP you can use this:

link = line.split('.')
if len(link) > 3 and link[-1].isalpha():
    plink = link[-3:]

This will ignore 2. and 3., while proceeding the 5. correctly (as SilentGhost correctly noted, your code ignores the 5.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM