如何让Python输入代码忽略特定字符串?含整数输入场景的处理问询
Hey there! Let's break down how to solve your two main goals: ignoring specific text like "I'm" from user input, and filtering out irrelevant content when trying to parse integers.
1. Ignoring Specific Text Strings (like "I'm")
To strip out a specific string from user input, you can use Python's built-in str.replace() method. It replaces all occurrences of the target string with an empty string, and then you can clean up extra whitespace with str.strip().
For example, if a user types "I'm Fred" when asked for their name, we can convert that to just "Fred":
raw_name_input = input("What is your name human? ") # Remove "I'm" and clean up extra spaces name = raw_name_input.replace("I'm", "").strip()
This works for any fixed string you want to ignore—just swap out "I'm" with whatever text you need to exclude.
2. Handling Integer Input with Irrelevant Content
When asking for age, users might include extra text (like repeating their name or "I'm"). Instead of forcing them to type only numbers, we can extract the numeric part from their input. The easiest way to do this is with regular expressions, which let you search for patterns (like digits) in a string.
First, you'll need to import the re module (Python's regex library). Then, use re.findall() to pull out all sequences of digits from the input. Here's how to integrate this into your age-checking loop:
Modified Full Code
import re # Get and clean the name input raw_name_input = input("What is your name human? ") name = raw_name_input.replace("I'm", "").strip() while True: try: raw_age_input = input(f"How old are you {name}? ") # Remove "I'm" from the age input first cleaned_age_input = raw_age_input.replace("I'm", "").strip() # Extract all digits from the cleaned input age_digits = re.findall(r'\d+', cleaned_age_input) if not age_digits: # No digits found—raise ValueError to trigger the except block raise ValueError # Convert the first set of digits to an integer age = int(age_digits[0]) if age >= 50: print(f"{age}! Wow {name}, you're older than most of the oldest computers!") else: print(f"Ahh, {name}, {age} isn't that old.") break except ValueError: print("No, I asked how old you were... ") print("Let us try again.")
How This Works:
re.findall(r'\d+', cleaned_age_input)looks for one or more digits (\d+) in the input and returns them as a list. For example, if the user types "How old are you I'm Fred? I'm 25", this will return['25'].- We check if the list is empty (no digits found) and raise a
ValueErrorif so, which triggers the error message. - We take the first set of digits (
age_digits[0]) and convert it to an integer—this handles cases where the user might accidentally type extra numbers too.
Testing the Example Scenarios
Q: What is your name human?
A: I'm Fred
The code cleans this toname = "Fred"
Q: How old are you Fred?
A: I'm 25
The code removes "I'm", extracts "25", and prints: "Ahh, Fred, 25 isn't that old."
This approach makes your program more flexible and user-friendly, since users don't have to type perfectly formatted input.
内容的提问来源于stack exchange,提问作者cheifmouthnoshut

