如何在python中检查空白输入

2024-04-16 23:26:19 发布

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

我对编程和python很陌生。我正在编写一个脚本,如果客户键入空白,我想退出脚本。 问题是我怎么做对? 这是我的尝试,但我认为是错误的

例如

userType = raw_input('Please enter the phrase to look: ')
userType = userType.strip()

line = inf.readline()
while (userType == raw_input)
    print "userType\n"

    if (userType == "")
        print "invalid entry, the program will terminate"
        # some code to close the app

Tags: theto脚本inputraw客户键入编程
3条回答

您提供的程序不是有效的python程序。因为你是个初学者,对你的程序做一些小的改动。它应该运行并且做我理解的事情。在

这只是一个起点:结构不清晰,你必须根据需要改变。在

userType = raw_input('Please enter the phrase to look: ')
userType = userType.strip()

#line = inf.readline() <-- never used??
while True:
    userType = raw_input()
    print("userType [%s]" % userType)

    if userType.isspace():
        print "invalid entry, the program will terminate"
        # some code to close the app
        break

您可以在您的输入中strip all whitespaces并检查是否还有任何内容。在

import string

userType = raw_input('Please enter the phrase to look: ')
if not userType.translate(string.maketrans('',''),string.whitespace).strip():
      # proceed with your program
      # Your userType is unchanged.
else:
      # just whitespace, you could exit.

我知道这是旧的,但这可能对将来的人有所帮助。我想出了如何用regex来做这个。这是我的代码:

import re

command = raw_input("Enter command :")

if re.search(r'[\s]', command):
    print "No spaces please."
else:
    print "Do your thing!"

相关问题 更多 >