如何在Python 3中无需导入模块格式化输入的无格式电话号码?
Hey Jonathan, great question! Since you're sticking to basic Python tools—no modules, just loops and conditionals—here's a practical, easy-to-follow solution to format that 10-digit phone number:
Step-by-Step Implementation
First, we'll validate the input to make sure it's exactly 10 digits (no letters or symbols), then format it into the (XXX)-XXX-XXXX pattern.
Full Code Example
# Get unformatted input from the user raw_phone = input("Enter a 10-digit phone number (no dashes/parentheses): ") # Validate the input is valid is_valid = True # Check length first if len(raw_phone) != 10: is_valid = False else: # Use a for loop to verify every character is a digit for char in raw_phone: if not char.isdigit(): is_valid = False break # Exit loop early if we find a non-digit # Handle validation result and format if valid if not is_valid: print("Oops! Please enter a valid 10-digit number with no extra characters.") else: # Simple formatting using string slicing (super readable) formatted_phone = f"({raw_phone[:3]})-{raw_phone[3:6]}-{raw_phone[6:]}" print(f"Here's your formatted number: {formatted_phone}")
Alternative: Using a For Loop to Build the Formatted String
If you prefer to use a loop for the formatting step (to stick closer to the constructs you're comfortable with), here's that version:
if is_valid: formatted = "(" # Start with the opening parenthesis for index in range(10): formatted += raw_phone[index] # Add closing parenthesis and dash after 3rd digit if index == 2: formatted += ")-" # Add dash after 6th digit elif index == 5: formatted += "-" print(f"Formatted number (loop method): {formatted}")
How It Works
- Validation: We first check if the input is exactly 10 characters long. Then we loop through each character to ensure they're all digits—if any non-digit is found, we mark the input as invalid and break the loop early.
- Formatting: The slicing method is quick and clean: we split the 10-digit string into three parts (first 3, middle 3, last 4) and wrap them in the required symbols. The loop version builds the string character by character, inserting the parentheses and dashes at the correct positions using conditionals.
内容的提问来源于stack exchange,提问作者Jonathan
相关产品推荐
相关产品推荐

