简体   繁体   English

删除IP地址的最后一个八位位组

[英]Deleting the last octets of an IP address

This is my code: 这是我的代码:

ip = ("192.143.234.543/23 
       192.143.234.5/23 
       192.143.234.23/23")

separateOct = (".")
ipNo4Oct = line.split(separateOct, 1) [0] 
print (ipNo4Oct)

The IPs come from a text file and I have done my for loops right. IP来自文本文件,我已经完成了for循环。

The result I get is: 我得到的结果是:

192
192
192

But I want this result: 但是我想要这个结果:

192.143.234
192.143.234
192.143.234

How do I get the result I want? 我如何获得想要的结果?

You can use almost the same code, with some slicing and join : 您可以使用几乎相同的代码,并进行切片和join

>>> ipNo4Oct = ip.split(separateOct) [0:3]
>>> '.'.join(ipNo4Oct)
'192.143.234'

Or for the entire string (considering it can be splitted to lines as your code suggests): 或对于整个字符串(考虑到可以按照代码提示将其拆分为几行):

>>> for line in ip:
        ipNo4Oct = line.split(separateOct) [0:3]
        '.'.join(ipNo4Oct)

'192.143.234'
'192.143.234'
'192.143.234'

With

ip = ("192.143.234.543/23",
       "192.143.234.5/23",
       "192.143.234.23/23")

for line in ip:
    separator = "."
    ipNo4Oct = separator.join(line.split(separator, 3)[:-1])
    print (ipNo4Oct)

you re-join your 3 parts using the separator. 您可以使用分隔符重新加入3个部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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