2012-03-27 63 views
0

我对编程和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 

回答

2

您提供的方案是不是一个有效的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 
0

将带去除空白后,用这个来代替:

if not len(userType): 
    # do something with userType 
else: 
    # nothing was entered 
0

你可以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. 
3

我知道这是旧的,但这可能有助于未来的人。我想出了如何用正则表达式来做到这一点。这里是我的代码:

import re 

command = raw_input("Enter command :") 

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