Python要求用户在inpu中输入特定的文本

2024-05-03 07:41:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,在输入验证方面遇到了问题。具体来说,我要求用户输入一个URL,但我要确保他们输入的是“http”或“https”作为URL的一部分。这就是我一直在做的:

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”。任何帮助都将不胜感激。谢谢。你知道吗


Tags: or用户httpshttpurlinputyourraw
3条回答

正如John Gordon在评论中所说,正确的方法是这样的:

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只是一个字符串,这意味着它总是真的,所以不管您的输入是什么,您最终总是运行循环。你知道吗

一些额外的评论:

要检查url,您需要查看“http”是否位于url的开头,因为://google.http.com不是有效的url,因此更好的方法是:while not user_url.startswith("http") and not user_url.startswith("https"):

您应该使用:

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: ")

解决方案是:

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。因此,您应该使用regex或使用以下命令:

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

相关问题 更多 >