2012-03-27 57 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!"