如何在Python中将单次输入的多个字符串添加到列表中
Hey Sara, glad you asked this—this is a super common task when handling user input, and there are a few straightforward ways to do it in Python depending on how robust you need the solution to be. Let's walk through them:
Basic Solution (Works for Most Simple Cases)
If your users are inputting words separated by commas (with or without spaces after commas), you can split the input string by commas and then clean up each word to remove extra whitespace.
Here's the code:
# Prompt the user for input user_input = input("输入一些单词:") # Split the input by commas, then strip whitespace from each word word_list = [word.strip() for word in user_input.split(',')] # Print the result to verify print(word_list)
How it works:
user_input.split(',')takes the input string (like"apple, house, fire, guitar") and splits it into a list of strings at every comma:['apple', ' house', ' fire', ' guitar']- The list comprehension uses
word.strip()to remove any leading/trailing spaces from each element, resulting in the clean list:['apple', 'house', 'fire', 'guitar']
Handle Edge Cases (Like Empty Entries or Quoted Words)
If you need to account for things like accidental trailing commas (e.g., "apple, house, ") or words that contain spaces/commas (wrapped in quotes), you can use Python's built-in csv module for a more robust solution.
import csv from io import StringIO user_input = input("输入一些单词:") # Use csv reader to parse the input, skipping initial spaces after commas reader = csv.reader(StringIO(user_input), skipinitialspace=True) # Extract the first (and only) row of parsed words word_list = next(reader) print(word_list)
Why this is useful:
- It automatically ignores empty entries from trailing commas: if input is
"apple, house, ", you'll get['apple', 'house']instead of including an empty string. - It correctly handles quoted words with commas or spaces, like input
"apple, 'big red house', fire"will result in['apple', 'big red house', 'fire']—something the basic split method would mess up.
Filter Out Empty Strings (Optional)
If you stick with the basic method but want to avoid empty entries from trailing commas or accidental extra spaces, just add a check to filter out empty strings after stripping:
word_list = [word.strip() for word in user_input.split(',') if word.strip()]
That's it! Pick the method that fits your use case—for simple word inputs, the basic solution is perfect. For more complex scenarios, the csv module has you covered.
内容的提问来源于stack exchange,提问作者Sara

