在我的程序中,用户将以"AB123“格式输入多个代码。根据输入的代码,我必须过滤掉那些以字母"AB“开头,以数字"00”结尾的代码。我必须打印和计数他们的数量与所有的代码分开,这是怎么做的呢?
我当前的代码是:
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”,但它没有按计划工作……
发布于 2020-11-01 12:23:10
您需要使用for
循环,并添加括号以使其成为列表理解:
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()
输入:
Please enter all codes of your products in format 'AB123':AB100 UI812 GS901 AB300
输出
Your codes are: AB100 UI812 GS901 AB300
Ok, here are your prioritized codes ['AB100', 'AB300']
https://stackoverflow.com/questions/64628613
复制相似问题