Reputation: 33
I have an IP address in my code Python 3.0 and I want to replace last octet to 0.
For example, host = 10.10.10.15
to host_changed = 10.10.10.0
Upvotes: 0
Views: 4809
Reputation: 7268
you can try:
host = "10.10.10.15"
host_list = host.split(".")[:-1]
host_list.append("0")
host = ".".join(host_list)
print(host)
Output:
10.10.10.0
Upvotes: 0
Reputation: 7206
Use .rfind()
The rfind()
method finds the last occurrence of the specified value.
host = "10.10.10.15"
host = host[:host.rfind('.')+1] + '0'
print (host)
output:
10.10.10.0
Upvotes: 1
Reputation: 3406
Assuming ip
is a string, you can use '.'.join(ip.split('.')[:-1]+["0"])
For instance,
>>> ip = '10.123.43.15'
>>> '.'.join(ip.split('.')[:-1]+["0"])
'10.123.43.0'
Upvotes: 0