将IP地址作为输入时出现Python语法错误

时间:2014-09-07 10:08:40

标签: python

我有一个名为sample_ips.txt的文本文件,其中包含一些随机IP地址,如下所示: -

182.0.0.15
182.0.0.16
182.0.0.17

我提供了一个IP地址作为输入来检查文本文件中是否存在IP,它打印为true,否则为false。

这是我的代码段: -

ip_input = str(input("Enter IP:"))
ip = open("sample_ips", "r")
data = ip.readlines()
for ips in data:
    ips = ips.strip("\n")
    if ip_input in ips:
        print "true"
    else:
        print "false"

抛出语法错误

File "<string>", line 1
182.0.0.15
    ^
SyntaxError: invalid sytanx

我认为尽管我在代码中将其声明为字符串,但它无法将输入作为字符串。有帮助吗? 感谢

2 个答案:

答案 0 :(得分:0)

input_ip = raw_input("Enter IP:") # In python 2.x. If you use input() then type your inputs as string (>>Enter IP:"182.0.0.15")
#input_ip = input("Enter IP:")  for python 3.x

with open("ip.txt", "r") as ip:
    data = ip.readlines()
    for ips in data:
        ips = ips.strip("\n")
        if input_ip in ips:
            print ("true")
        else:
            print ("false")

答案 1 :(得分:-1)

嗯,这很有效:

input = raw_input("Enter IP:")
ip = open("sample_ips.txt", "r")
data = ip.readlines()
for ips in data:
    ips = ips.strip("\n")
    if input in ips:
        print "true"
    else:
        print "false"

Working for me

:编辑:

Python3版

input = input("Enter IP:")
ip = open("sample_ips.txt", "r")
data = ip.readlines()
for ips in data:
    ips = ips.strip("\n")
    if input in ips:
        print ("true")
    else:
        print ("false")