所以我做了一个游戏的刽子手,它开始与一个“僵尸大师”输入一个字符串,然后有多少猜测,玩家将不得不尝试猜测字符串。我只是刚刚开始,我正在尝试编写一个函数来检查BotMaster输入的内容是否是有效的字符串。一个有效的字符串应该是一个只有字母、没有符号、数字或额外空格的字符串。我已经有了一些函数,它们可以删除多余的空格和非alpha输入(因此它可以去掉句点、多余的空格等等),还有一个函数可以将它们全部小写,但是如果我输入一个数字或一个空字符串,我的函数就会中断。我该如何添加这些?你知道吗
#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\u 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
我该怎么解决这个问题?你知道吗
正如johngordon已经提到的,解决方案是“str”类的方法“isalpha”。你知道吗
询问\u bot()
while循环在编写时总是在函数中终止。你知道吗
您的代码被编辑为工作:
正如其他答案已经提到的,你可以使用isalpha街()若要检查字符串是否有效,或者如果要修改字符串,则需要调整check_alpha函数,如下所示:
相关问题 更多 >
编程相关推荐