Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python newbie, equal to a string?

Tags:

python

regex

Trying to get my head arround why I cannot match the output of the IP against a set IP and therefore render a outcome.

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"

The result is always "BAAD"

like image 240
user2961119 Avatar asked Nov 06 '13 15:11

user2961119


People also ask

Can you use == for strings in Python?

Python comparison operators can be used to compare strings in Python. These operators are: equal to ( == ), not equal to ( != ), greater than ( > ), less than ( < ), less than or equal to ( <= ), and greater than or equal to ( >= ).

How do I equal a string in Python?

String Equals Check in Python In python programming we can check whether strings are equal or not using the “==” or by using the “. __eq__” function. Example: s1 = 'String' s2 = 'String' s3 = 'string' # case sensitive equals check if s1 == s2: print('s1 and s2 are equal.

What is a string in Python beginner?

A string is usually a bit of text (sequence of characters). In Python we use ” (double quotes) or ' (single quotes) to represent a string. In this guide we will see how to create, access, use and manipulate strings in Python programming language.

How do I check if a string matches in Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.


1 Answers

re.findall returns a list of matches, not a string. So you've two options now, either iterate over the list and use 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"  

or use 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"  
like image 88
Ashwini Chaudhary Avatar answered Oct 19 '22 03:10

Ashwini Chaudhary