Python新手,等于一个字符串?

时间:2013-11-06 15:36:04

标签: python regex

试图解决为什么我无法将IP的输出与设定的IP匹配,从而产生结果。

import urllib
import re

ip = '212.125.222.196'

url = "http://checkip.dyndns.org"

print url

request = urllib.urlopen(url).read()

theIP = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", request)

print "your IP Address is: ",  theIP

if theIP == '211.125.122.192':
    print "You are OK"
else:
    print "BAAD"

结果总是“BAAD”

4 个答案:

答案 0 :(得分:6)

re.findall返回匹配列表,而不是字符串。所以你现在有两个选择,要么迭代列表并使用any

theIP = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", request)
if any(ip == '211.125.122.192' for ip in theIP):
    print "You are OK"
else:
    print "BAAD"  

#or simply:

if '211.125.122.192' in theIp:
    print "You are OK"
else:
    print "BAAD"  

或使用re.search

theIP = re.search(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", request)
if theIP and (theIP.group() == '211.125.122.192'):
    print "You are OK"
else:
    print "BAAD"  

答案 1 :(得分:0)

这是因为您将列表与字符串进行比较。可能的解决方案(取决于您的需求):

if any(ip == '211.125.122.192' for ip in theIP):

- >检查找到的任何IP地址是否匹配

if theIP and theIP[0] == '211.125.122.192':

- >检查列表是否为空,以及首次找到的IP地址是否匹配。

如果结果始终只包含一个IP地址,那么您可以re.findall代替re.search而不是proposed by hcwhsa

答案 2 :(得分:0)

re.findAll返回一个列表,而不是字符串!

你必须抓住字符串:

theIP = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", request)[0]

或者,只需检查搜索结果中是否包含ip

if ip in theIP:
    print "You are OK"

或使用re.search

theIP = re.search(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", request)

答案 3 :(得分:0)

theIP不是字符串,它是一个列表。参见文档

>>> print re.findall.__doc__
Return a list of all non-overlapping matches in the string.

    If one or more groups are present in the pattern, return a
    list of groups; this will be a list of tuples if the pattern
    has more than one group.

    Empty matches are included in the result.

您可能想要执行类似

的操作
for ip in theIP:
    if ip == '211.125.122.192':
        print 'You are ok :)'

但是,获取你的ip可能比访问网页和解析结果要好得多。也许你可以使用hostname -Isubprocess?也许这样的事情会更好吗?

import subprocess

theIP = subprocess.check_output(['hostname','-I'])