我想弄清楚为什么我无法将 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"
结果总是“糟糕”
最佳答案
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"
关于Python新手,等于字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19816220/