首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在使用.isalpha时对用户输入进行错误检查

如何在使用.isalpha时对用户输入进行错误检查
EN

Stack Overflow用户
提问于 2021-05-21 02:21:53
回答 2查看 31关注 0票数 0

所以我正在尝试设计一个模拟花园的程序,这是我编写的函数之一,它是用户输入植物名称的一个函数,例如羊齿植物或苹果树。

代码语言:javascript
复制
def add_plant(plant_list, total_food,):
    new_plant = get_valid_name("")
    if new_plant in plant_list:
        print("invalid choice")
    elif len(new_plant) > total_food:
            print(f"{new_plant} would cost {len(new_plant)} food. with only {total_food}, you can't afford it")
    else:
        plant_list.append(new_plant.title)
        used_food = len(new_plant)
        total_food -= used_food
    return total_food

我的代码如下,我这样写它的原因是我想确保程序在没有输入任何东西或用户输入数字的情况下循环回来。但我发现,当我试图通过添加红薯或苹果树等植物来测试它时,我得到的结果是无效的选择打印。

我想知道如何编码这个错误检查,以便它检查空格和数字,同时还允许用户输入长度超过一个单词的植物名称。

代码语言:javascript
复制
def get_valid_name(plant,):
    while True:
        plant = input("Enter plant name:").title()
        if plant.isalpha():
            return true
        else:
            print("Invalid plant name")
EN

回答 2

Stack Overflow用户

发布于 2021-05-21 02:33:29

使用string.replace()删除空格,并为每个字符测试isdigit()isalpha()

Pythons any()函数将在迭代时测试是否满足任何条件,因此测试字符是否既不是数字也不是字母字符。它还短路,所以它比列表理解更快。

代码语言:javascript
复制
def get_valid_name(plant):
    is_valid = False
    while not is_valid:
        plant = input("Enter plant name:").title()
        without_spaces = plant.replace(' ', '')
        is_valid = not(any(!(c.isdigit() or c.isalpha()) for c in without_spaces))
    return plant
票数 0
EN

Stack Overflow用户

发布于 2021-05-21 02:49:53

像这样怎么样?

代码语言:javascript
复制
def get_valid_name():
    while (plant := input().strip()).isdigit() or not plant: pass
    return plant.title()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67626007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档