[英]Define IP address in string and replace last octet
I have an IP address in my code Python 3.0 and I want to replace last octet to 0. 我的代码Python 3.0中有一个IP地址,我想将最后一个八位位组替换为0。
For example, host = 10.10.10.15
to host_changed = 10.10.10.0
例如, host = 10.10.10.15
到host_changed = 10.10.10.0
Use .rfind()
使用.rfind()
The rfind()
method finds the last occurrence of the specified value. rfind()
方法查找指定值的最后一次出现。
host = "10.10.10.15"
host = host[:host.rfind('.')+1] + '0'
print (host)
output: 输出:
10.10.10.0
Assuming ip
is a string, you can use '.'.join(ip.split('.')[:-1]+["0"])
假设ip
是一个字符串,则可以使用'.'.join(ip.split('.')[:-1]+["0"])
For instance, 例如,
>>> ip = '10.123.43.15'
>>> '.'.join(ip.split('.')[:-1]+["0"])
'10.123.43.0'
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.