【问题标题】:How to only allow number as input? - Python [duplicate]如何只允许数字作为输入? - Python [重复]
【发布时间】:2018-08-05 04:54:44
【问题描述】:

我想制作一个仅具有 IP 格式的简单 Python IP 跟踪器,但我很困惑,因为我无法过滤输入。 这是我的代码:

while True:
    ip= raw_input("What Your Target IP : ")
    url = "http://blabla.com/json/"
    response = urllib2.urlopen(url + ip)
    data = response.read()
    values = json.loads(data)

    print("------------------------------------")
    print "\r"
    print(" IP: " + values['query'])
    print(" City: " + values['city'])
    print(" Region: " + values['regionName'])
    print(" Country: " + values['country'])
    print(" Time Zone: " + values['timezone'])
    print "\r"

    break

【问题讨论】:

  • 使用 stdlib ipaddress 模块。
  • 您的标题具有误导性。您不想检查数字,而是要检查有效的 IP 地址。

标签: python input


【解决方案1】:

您可以使用正则表达式或IP地址模块来解决您的问题

import re
import os
import urllib2
import json
while True:
    ip = raw_input("What Your Target IP : ")
    if not re.match(("^\d{0,9}\.\d{0,9}\.\d{0,9}\.\d{0,9}$"), ip):
        print ("Error! Make sure you only use numbers")
    else:
        print("You picked number "+ ip)
        url = "https://blablabla/"
        response = urllib2.urlopen(url + ip)
        data = response.read()
        values = json.loads(data)

print("------------------------------------")
print "\r"
print(" IP           :  " + values['ip'])
print(" City         :  " + values['city'])
print(" Region       :  " + values['region'])
print(" Country      :  " + values['country_name'])
print(" Continent    :  " + values['continent_name'])
print(" Time Zone    :  " + values['time_zone'])
print(" Currency     :  " + values['currency'])
print(" Calling Code :  " + "+" + values['calling_code'])
print(" Organisation :  " + values['organisation'])
print(" ASN          :  " + values['asn'])
print "\r"

【讨论】:

  • 我这里出错了,但我不知道如何在评论中使用代码格式。
  • print ("Error! Make sure you only use numbers") ^ IndentationError: unindent does not match any outer indentation level
  • 出现错误)
  • 检查这个link
  • 您的缩进与此处建议的答案不符
猜你喜欢
  • 2021-01-15
  • 2017-08-11
  • 2015-02-26
  • 1970-01-01
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 2021-11-18
相关资源
最近更新 更多