如何在python中不接受空白和空格只有raw_input的回复?

时间:2015-09-29 09:41:08

标签: python-2.7 whitespace

newname = 3
while (newname>0):
    Create_Login =raw_input("Create login name: ")
    if Create_Login == (""):
        newname=newname-1
        print "error! Please do not leave it blank"
    elif Create_Login == (" ") or Create_Login == ("  ") or Create_Login == ("   ") or Create_Login == ("    ")  or Create_Login == ("     "):
        newname=newname-1
        print "error! Please do not spam the spacebar!"
    else:
        newname=-2
if newname!=-2:
    #back to menu code and the rest...

我有一个像这样的代码来在我的程序中创建新用户,但

Create_Login =raw_input("Create login name: ")

它接受来自用户的任何类型的输入作为其用户名。我想限制Create_Login拒绝无效输入,例如

[ "", " ", "  ", "   ",...] #and so on

我该怎么做?

2 个答案:

答案 0 :(得分:4)

你试过isspace()吗?

isspace()检查字符串是否只是空格而不需要像strip()那样创建新的字符串对象

if(not Create_Login or Create_Login.isspace()):
    print "User has not entered anything"

您也可以尝试strip()。但是就像我之前说的那样,它会创建一个新的字符串对象。

strip()删除了前导空格和trialling空格。因此它只会删除前导和尾随空格,而不会删除字符串中的空格。

Create_Login = raw_input("Create login name: ")
if not Create_Login.strip():
    print "User has not entered anything"

答案 1 :(得分:0)

谢谢大家的关心〜 最近,我发现了一个非常有用和简单的方法来解决这个问题。

#by doing .strip
Create_Login = raw_input('new username: ')
Create_Login = str(Create_Login.strip(' '))

这个新行将Create_login读作字符串并删除其中的所有空格以创建一个没有空格的有效用户名。

#e.g.: "A  B" = "AB", "   C" = "C", or "  "=""