Modify Python String Clear the last part of the IP

Asked 2 years ago, Updated 2 years ago, 12 views

I want to extract the ip address and erase only 555 parts when 123.456.789.555 comes out, but 555 can be two or three digits, and it's not a fixed number, so I don't know what to do with it

python

2022-09-21 11:32

3 Answers

ip= "123.456.789.555"
print('.'.join(ip.split('.')[:-1])) # 123.456.789

Separate the letter with . and subtract the last part.


2022-09-21 11:32

ip="123.456.789.555"
Extracted ip=""
if len(ip) == 15:
    extracted ip + = ip[:-3]
elif len(ip) ==14:
    extracted ip +=ip[:-2]
extracted ip  


2022-09-21 11:32

Find . from the back to find out its location, and cut the string to that location. An exception occurs in rindex when the string does not contain ..

ip = '1.1.1.1'
Last Point Location = ip.rindex('.')
ip3 = ip[:Last Point Location]
print(ip3, ip)


2022-09-21 11:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.