如何在Python中实现用户无间隔的同一行输入?
Got it, the problem with your current code is that it uses split() which relies on spaces to separate the numbers and operator. When users input something like 3+5 or 10.2*4 without any spaces, split() can't break it into three parts (x, y, z), so your code will throw an error. Let's fix this with two practical approaches:
Approach 1: Regular Expressions (Robust & Flexible)
Regular expressions are perfect here because they can easily parse numbers (including decimals and negatives) and operators from a single continuous string. Here's a ready-to-use implementation:
import re # Get space-free input from user user_input = input("Enter number (e.g., 3+5 or -4*2.5): ") # Regex pattern to match valid numbers and operators # Breakdown: # - (\-?\d+\.?\d*): Matches optional negative sign, digits, optional decimal, more digits # - ([+\-*/]): Matches one of the four arithmetic operators # - (\-?\d+\.?\d*): Matches the second number (same rules as the first) match = re.match(r'(\-?\d+\.?\d*)([+\-*/])(\-?\d+\.?\d*)', user_input) if match: # Extract the captured values x = float(match.group(1)) op = match.group(2) z = float(match.group(3)) # Perform the calculation if op == "+": value = x + z elif op == "-": value = x - z elif op == "*": value = x * z elif op == "/": if z == 0: print("Error: Cannot divide by zero!") exit() value = x / z print(f"Result: {value}") else: print("Invalid input format! Please enter like '3+5', '-10/2', or '6.7*3'")
This approach handles all common cases: positive/negative numbers, decimals, and all four operators. It also includes basic error handling for invalid inputs and division by zero.
Approach 2: Manual String Traversal (Simple for Basic Scenarios)
If you prefer not to use regex, you can manually scan the input string to locate the operator's position:
user_input = input("Enter number (e.g., 3+5): ") operators = '+-*/' op_position = -1 # Loop through each character to find the operator (skip leading negative sign) for idx, char in enumerate(user_input): if char in operators and idx != 0: op_position = idx break if op_position == -1: print("Invalid input: No valid operator found!") else: try: # Split the string into numbers and operator x = float(user_input[:op_position]) op = user_input[op_position] z = float(user_input[op_position+1:]) except ValueError: print("Invalid input: Please enter valid numbers and operator!") exit() # Calculation logic if op == "+": value = x + z elif op == "-": value = x - z elif op == "*": value = x * z elif op == "/": if z == 0: print("Error: Cannot divide by zero!") exit() value = x / z print(f"Result: {value}")
Note: This basic version works for most standard inputs but might struggle with edge cases like negative second numbers (e.g., 5+-3). For full robustness, the regex approach is recommended.
内容的提问来源于stack exchange,提问作者red wing

