【问题标题】:How to check for white space input in python如何在python中检查空格输入
【发布时间】:2012-03-27 18:52:56
【问题描述】:

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

【问题讨论】:

    标签: python file-io


    【解决方案1】:

    我知道这已经过时了,但这可能会对将来的某个人有所帮助。我想出了如何用正则表达式做到这一点。这是我的代码:

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

    【讨论】:

      【解决方案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
      

      【讨论】:

        【解决方案3】:

        您可以在输入中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.
        

        【讨论】:

          【解决方案4】:

          应用条删除空格后,改用这个:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-01-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-07-14
            • 2020-09-16
            相关资源
            最近更新 更多