如何检查输入值是否为有效字符串?

时间:2019-11-07 16:56:55

标签: python

所以我正在制作一个hang子手游戏,它从“ BotMaster”输入一个字符串开始,然后是该玩家必须尝试猜测字符串的多少个猜测。我才刚刚开始,并且正在尝试编写一个函数,该函数将检查BotM​​aster放置的内容是否为有效字符串。有效字符串应为仅字母,没有符号,数字或多余空格的字符串。我已经具有删除多余空格和非字母输入(因此会占用句点,多余空格等)的功能,并使其全部变为小写,但是如果我输入数字为空字符串,我的功能就会损坏。我应该如何添加这些?

#Imports (this is for later code I haven't written)
import os,time,random

#Removes extra spaces from the function
def space_cull(the_str):
  result = the_str 
  result = result.strip()
  result =" ".join(result.split())
  the_str = result
  return the_str

#Makes the string lowercase
def make_lower(the_str):
  the_str = the_str.lower()
  return the_str

#Checks if everything in the string are Alpha Inputs
def check_alpha(the_str):
  the_str =''.join([char for char in the_str if char.isalnum()])
  return the_str 

#Ask Botmaster the string they want
def ask_bot():
  while True:
   bot_str = input('Enter a string for the player to guess: ')
   bot_str = space_cull(bot_str)
   bot_str = make_lower(bot_str)
   bot_str = check_alpha(bot_str)
   if bot_str == '':
      print('That is not a correct string, try again')
      True
   return bot_str

ask_bot()

我添加了ask_bot()部分,以便可以更快地测试该功能 这就是发生的情况:

Enter a string for the player to guess: 1
#nothing 
#Tested again:
Enter a string for the player to guess: ''
That is not a correct string, try again.
#But then exits the loop, which I don't want it to, if the string is wrong I want it to ask them again.
#Tested Again
Enter a string for the player to guess: 'Katze'
#Nothing, which is actually good this time

我该如何解决?

3 个答案:

答案 0 :(得分:1)

您的while循环将始终在编写函数时终止。

def ask_bot():
  while True:
   bot_str = input('Enter a string for the player to guess: ')
   bot_str = space_cull(bot_str)
   bot_str = make_lower(bot_str)
   bot_str = check_alpha(bot_str)
   if bot_str == '':
      print('That is not a correct string, try again')
      True # <- this does nothing
   return bot_str # < - this breaks out of the function and the loop

您的代码已修改为可以正常工作:


def ask_bot():
  while True:
   bot_str = input('Enter a string for the player to guess: ')
   bot_str = space_cull(bot_str)
   bot_str = make_lower(bot_str)
   bot_str = check_alpha(bot_str)
   if bot_str == '':
      print('That is not a correct string, try again')
   else: # returns the string if the input is correct
      return bot_str # this still breaks out of the function and the loop
                     # but only if the string has passed the checks

正如已经提到的其他答案一样,您可以使用str.isalpha()来检查字符串是否有效,或者如果您想就地修改字符串,则需要像下面这样调整您的check_alpha函数:

def check_alpha(the_str):
  the_str =''.join([char for char in the_str if char.isalpha()])
  return the_str 

答案 1 :(得分:0)

正如John Gordon所提到的,解决方案是“ str”类的“ isalpha”方法。

userInput = input("Your suggestion: ")
if userInput.isalpha():
    # do some magic
else:
    print("please only type in letters")

答案 2 :(得分:0)

  

您根本不需要check_alpha(str)函数。如下修改ask_bot()。

filter

ask_bot()