2017-06-12 53 views
0

我是Python的新手,并且在输入验证时遇到问题。具体来说,我要求用户输入一个URL,但我想确保他们输入“http”或“https”作为其URL的一部分。这就是我一直在做:Python--要求用户输入某些文本作为其输入的一部分

user_url = raw_input(please enter your URL:) 
while "https" or "http" not in user_url: 
    print "you must enter a valid URL format, try again" 
    user_url = raw_input(please enter your URL:) 

当我使用此代码,任何文本仍可接受,即使它不包含“http”或“https”开头。任何帮助将不胜感激。谢谢。

+1

你必须明确地说明每个条件:'while“https”不在user_url中,而“http”不在user_url中:' –

回答

-1

你应该使用:

user_url = raw_input("please enter your URL: ") 
while user_url.find("http") != -1: 
    print "you must enter a valid URL format, try again" 
    user_url = raw_input("please enter your URL: ") 
+0

上次忘记了很大一部分问题。感谢您指出 – nikpod

-2
while "https" not in user_url and "http" not in user_url: 
0

解决的办法是:

while "https" not in user_url and "http" not in user_url: 

但:

while "http" not in user_url: 

足够的http包括在https

但是,以下内容将被视为正常:“www.domain.com/http”,因为它包含http。所以,你应该要么使用正则表达式或使用以下命令:

while user_url[:4] != "http": 
0

正如约翰·戈登在评论中说,正确的方法来做到这一点是这样的:

while "https" not in user_url and "http" not in user_url: 

你有什么不工作因为,当你写的,Python看到有进行评估,看看他们是真的还是假的两个语句: 1. "https" 2. "http" not in user_url

一个非空字符串的真值总是True(可以用bool("somestring")查询)。 因为语句1只是一个字符串,所以它意味着它总是真实的,所以无论您的输入是什么,最终都会运行循环。

一些其它附加注释:

要检查一个网址,你要看看“HTTP”是在URL,因为开始“://google.http.com”不是一个有效的URL ,所以更好的方法是:while not user_url.startswith("http") and not user_url.startswith("https"):

相关问题