user6029333
user6029333

Reputation:

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.

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?

Upvotes: 2

Views: 2309

Answers (2)

Idos
Idos

Reputation: 15310

You can use almost the same code, with some slicing and 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'

Upvotes: 1

glglgl
glglgl

Reputation: 91017

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.

Upvotes: 0

Related Questions