Python干洗店服务程序:如何处理用户姓名输入首字母大写需求
Solution for Auto-Capitalizing Customer Names in Smiths Cleaners Program
Looking at your code, I'll help you fix both the name validation logic (which has a small bug) and implement automatic proper capitalization for customer names—even for multi-word names like "mary ann" or "JOHN DOE".
Modified Code
# Welcome message to the user print("Welcome to Smiths Cleaners, offering the best dry-cleaning service around!\n") # Loop to get valid customer name and auto-format it while True: name_input = input("What is the customer's name? ").strip() # Validate: ensure every word in the name is alphabetic (allows spaces between names) if all(word.isalpha() for word in name_input.split()): # Auto-format to proper case (each word's first letter capitalized) formatted_name = name_input.title() break print("Invalid input: please enter a name using only letters and spaces.") print(f"\nBelow is the price table for the services available for {formatted_name}")
Key Changes Explained
- Fixed Name Validation: Your original check
name.isalpha() or name.split()would accept invalid inputs like "123 " (numbers plus spaces). The new checkall(word.isalpha() for word in name_input.split())ensures every part of the name is made up of letters, while still allowing multi-word names (like first + last name). - Automatic Proper Capitalization: Instead of only using
capitalize()when printing (which only capitalizes the first word and lowercases the rest), we usetitle()to format the name as soon as it's validated. This handles all cases:- Input
john doe→ OutputJohn Doe - Input
JOHN DOE→ OutputJohn Doe - Input
jOhN sMiTh→ OutputJohn Smith
- Input
- Added
.strip(): This removes any accidental leading/trailing spaces from the user's input, so names like " jane " get cleaned up to "Jane".
内容的提问来源于stack exchange,提问作者Lauren.M
相关产品推荐
相关产品推荐

