简体   繁体   English

将group()转换为float或int格式

[英]Converting group() to float or int format

This is a followup to Python. 这是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. 我能够在文本文件中找到请求的IP地址。

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. 我的目标是以某种方式将字符串"10.226.27.60"转换为允许我在数学公式中使用的格式。 For example, I want to get another address "10.226.27.59" by subtracting 1 from the last octet of the original address. 例如,我想通过从原始地址的最后一个八位位组减去1得到另一个地址"10.226.27.59"

You can use the ipaddress module for Python 3: 您可以将ipaddress模块用于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 IPv4Address类允许算术运算符

Docs: https://docs.python.org/3/library/ipaddress.html#operators 文件: https//docs.python.org/3/library/ipaddress.html#operators

You could take the string (what you end up with): 您可以使用string (最终得到的结果):

s = "10.226.27.60"

and then split on '.' 然后在'.'split and use a list-comprehension to convert the parts to integers : 并使用list-comprehension将零件转换为integers

p = [int(i) for i in s.split('.')]

and then finally, subtract 1 from the last element: 最后,从最后一个元素中减去1

p[-1] -= 1

to get p as: 得到p为:

[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 : 请注意,如果要以原始string格式显示此列表,则可以将joingenerator-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 [10,226,27,60]您可以计算每个元素

convert back: 转换回:

string_again = ".".join(str(number) for number in number_list)
print(string_again)

10.226.27.60 10.226.27.60

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM