Python新手,等于字符串?

标签 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"

结果总是“糟糕”

最佳答案

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/

相关文章:

python - set_colorkey不取出背景颜色(python)

python - 将 Python 数据框列转换为日期格式

python - scipy/numpy 中 n > m 的矩形矩阵的 QR 分解

python - Coverage 无法将 'manage.py' 作为 Python 代码运行

python - 正则表达式 python 不会像我想要的那样工作

python - 从返回元组的函数创建新的 pandas 数据框列

javascript - 正则表达式,3个或更多字符,最少1个减号,最多3个数字

rewrite.xml 中的正则表达式

MySQL:小写或大写正则表达式安全吗?

正则表达式匹配日期格式 DD-MM-YYYY 和 DD/MM/YYYY