从Python上的字符串中提取整数值

时间:2016-12-25 20:35:54

标签: string python-2.7 shell integer

我经历过关于这个主题的每一篇文章都没有回答我的问题;

这是代码:
output = 'Scan results for BrainS (192.168.43.111) Scan results for Slave (192.168.43.107) Scan results for SlaveSmall (192.168.43.242)' while (True) if output[i].isdigit(): # i has initial value of 15, j=0 f[j]=output[i] j+=1 i+=1 elsif(i == len(output)): break else: i+=1 continue

打印:
>>>f ['1','9','2','1','6','8','4','3','1','1','1','0','0','0']

正如你所看到的那样,我正试图用点提取IP(在这段代码中,我并没有尝试提取点数,只提取数字), 我无法弄清楚如何获得我想要的字符串: f = 192.168.43.111

有什么建议吗?更好的命令?

2 个答案:

答案 0 :(得分:0)

对于字符串中的多对括号,我认为最好像这样使用正则表达式:

import re

output = '''Scan results for BrainS (192.168.43.111) 
            Scan results for Slave (192.168.43.107)
            Scan results for SlaveSmall (192.168.43.242)'''

f = re.findall(r'\(([^()]+)\)',output)
>>>['192.168.43.111', '192.168.43.107', '192.168.43.242']

试试here!

答案 1 :(得分:0)

在这里,这段代码将完成这项工作!

output = 'My computer IP is = (192.168.43.111) and yours not.'
ip=[]
ip_flag = False

for x in output:
    if x == '(':
        ip_flag = True
        continue
    if ip_flag:
        if x != ')':
            if x != '.': # remove this line of you want the dots
                ip.append(x)
        else:
            break
print(ip)
theIp="" 
for i in ip: 
    theIp+=i