首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python -向变量添加特定输入

Python -向变量添加特定输入
EN

Stack Overflow用户
提问于 2020-11-01 12:13:05
回答 1查看 36关注 0票数 1

在我的程序中,用户将以"AB123“格式输入多个代码。根据输入的代码,我必须过滤掉那些以字母"AB“开头,以数字"00”结尾的代码。我必须打印和计数他们的数量与所有的代码分开,这是怎么做的呢?

我当前的代码是:

代码语言:javascript
运行
复制
def main():
    code = input("Please enter all codes of your products in format 'AB123':")
    print("Your codes are:", code)
    pCodes = None

    if len(code) == 5 and code.startswith('AB') and code.endswith('00'):
        pCodes = code.startswith('AB') and code.endswith('00')
        print("Ok, here are your prioritized codes", pCodes)
    else:
        print("There are no codes with 'AB' letters and '00' digits at the end!")

main()

我尝试集成一个新的变量pCodes来给所有的代码分配字母"AB“和数字"00”,但它没有按计划工作……

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-01 12:23:10

您需要使用for循环,并添加括号以使其成为列表理解:

代码语言:javascript
运行
复制
def main():
    code = input("Please enter all codes of your products in format 'AB123':")
    print("Your codes are:", code)
    codes = [c for c in code.split() if len(c) == 5 and c[:2] == 'AB' and c[-2:] == '00']  
    if codes:
        print("Ok, here are your prioritized codes", codes)
    else:
        print("There are no codes with 'AB' letters and '00' digits at the end!")


main()

输入:

代码语言:javascript
运行
复制
Please enter all codes of your products in format 'AB123':AB100 UI812 GS901 AB300

输出

代码语言:javascript
运行
复制
Your codes are: AB100 UI812 GS901 AB300
Ok, here are your prioritized codes ['AB100', 'AB300']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64628613

复制
相关文章

相似问题

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