Is there a way to capitalise specific letters in a value in python?
本问题已经有最佳答案,请猛点这里访问。
对于一个作业,代码的一部分要求用户在3个输入之间进行选择。为了确保代码可以接受任何格式的选项,我使用了.lower(),如下所示。
1 2 3 4 5 6 | while True: RequestTea = input("What tea would you like? English Breakfast, Green Tea or Earl Grey?").lower() if RequestTea.lower() not in ('earl grey','english breakfast','green tea'): print("We do not offer that unfortunately, please choose again.") else: break |
为了确认用户的选择,我根据值使用了三种不同的打印,
1 2 3 4 5 6 | if RequestTea == 'earl grey': print("Earl Grey Tea selected!") if RequestTea == 'green tea': print("Green Tea selected!") if RequestTea == 'english breakfast': print("English Breakfast Tea selected!") |
号
为了将其减少到两行代码,我尝试将其打印("requesttea","selected"),但是我希望将tea名称显示为大写的第一个字母,输入为.lower()。我希望将TEA名称(请求TEA)显示为标题,然后以小写形式显示"已选择"。
非常感谢。
有另一种方式是在打印的报表:
1 2 3 4 5 6 7 8 | offered_tea = ('earl grey', 'english breakfast', 'green tea') while True: RequestTea = input("What tea would you like? English Breakfast, Green Tea or Earl Grey?") RequestTea_Lower = RequestTea.lower() if RequestTea_Lower in offered_tea: print(RequestTea_Lower.title(),' selected!') else: print("We do not offer that unfortunately, please choose again.") |
1 2 3 4 5 6 7 | offered_tea = ('earl grey', 'english breakfast', 'green tea') while True: RequestTea = input("What tea would you like? English Breakfast, Green Tea or Earl Grey?").lower() if RequestTea in offered_tea: print('{} selected!'.format(RequestTea.title())) else: print("We do not offer that unfortunately, please choose again.") |
10:
1 2 | What tea would you like? English Breakfast, Green Tea or Earl Grey? earl grey Earl Grey selected! |