[英]How to devide value and rejoin in python?
I'm working with IP, so on the loop it should be increasing the a
value to different devices to retrieve data.我正在使用 IP,因此在循环中它应该增加不同设备的
a
值以检索数据。 How do I change the a
value and rejoin as the IP address?如何更改
a
值并重新加入为 IP 地址?
ip = 192.168.10.a
a = 100 + n // assume n=5
// So a = 105
I need replace the IP a
to particular value, and rejoin it as IP
address.我需要将 IP 替换
a
特定值,并将其重新加入为IP
地址。
Expected output:预期 output:
ip = 192.168.10.105
// `n` is not a constant; it will change time to time.
Try this:尝试这个:
ip = "192.168.10.{}"
a = 100
for i in range(10): # assuming you want 10 IP addresses:
new_ip = ip.format(a)
print("Hello new_ip: {}".format(new_ip))
a += 5
if a > 255:
# do something about it
pass
I would suggest using a list to store and manipulate the ip and only convert it to a string for output afterward:我建议使用列表来存储和操作 ip,然后仅将其转换为 output 的字符串:
n = 5
ip = "192.168.10.0".split(".") # [192,168,10,0]
ip[3] = 100+n
print(".".join(map(str,ip))) # '192.168.10.105'
If your ip string actually contains the letter a
, you could replace it directly to form a new string:如果您的 ip 字符串实际上包含字母
a
,您可以直接替换它以形成一个新字符串:
ip = "192.168.10.a"
print(ip.replace("a",str(100+n))) # '192.168.10.105'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.