This is a followup to Python. How to print a certain part of a line after it had been "re.searched" from a file
Here is the initial code, based on the accepted answer to the linked question:
import re
VSP = input("Номер ВСП (четыре цифры): ")
c = re.compile('(\d+\.226\.\S+)\s+\S+' + VSP)
Tunnel0_IP_VSP = re.search(c, open('OUS_IP.txt').read())
print (Tunnel1_IP_VSP.group(1))
Номер ВСП (четыре цифры): 1020
10.226.27.60
I was able to find the requested IP address in text file.
My goal is to somehow convert the string "10.226.27.60"
to a format that would allow me to use it in mathematical formulas. For example, I want to get another address "10.226.27.59"
by subtracting 1 from the last octet of the original address.
You can use the ipaddress
module for Python 3:
>>> import ipaddress
>>> ip = ipaddress.IPv4Address('10.226.27.60')
>>> ip - 1
IPv4Address('10.226.27.59')
The IPv4Address
class allows for arithmetic operators
Docs: https://docs.python.org/3/library/ipaddress.html#operators
You could take the string
(what you end up with):
s = "10.226.27.60"
and then split
on '.'
and use a list-comprehension
to convert the parts to integers
:
p = [int(i) for i in s.split('.')]
and then finally, subtract 1
from the last element:
p[-1] -= 1
to get p
as:
[10, 226, 27, 59]
Note that if you want to display this list in the original string
format, then you can use join
with a generator-expression
:
".".join(str(i) for i in p)
#"10.226.27.60"
You can do:
string = "10.226.27.60".split(".")
number_list = [int(number) for number in string]
print(number_list)
[10, 226, 27, 60] you can calculate each element
convert back:
string_again = ".".join(str(number) for number in number_list)
print(string_again)
10.226.27.60
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.