Python中如何去除re.split()结果列表元素的左右空白
Hey there! Let's sort out that whitespace issue you're running into when splitting your string. Here are a couple of simple, effective ways to get your desired data_2 = ['2,000', '3,000'] result:
Method 1: Clean Up Split Results with List Comprehension + strip()
This approach takes your existing split result and removes whitespace from each element individually. strip() is a string method that removes leading/trailing whitespace (spaces, tabs, newlines, etc.):
import re data_1 = ' 2,000/3,000 ' # Your initial split split_data = re.split('/', data_1) # Clean each element with strip() data_2 = [item.strip() for item in split_data] print(data_2) # Output: ['2,000', '3,000']
Method 2: Split with Regex That Handles Whitespace Directly
Instead of splitting first then cleaning, you can adjust your regex pattern to account for whitespace around the / separator. This way, the split operation itself returns clean elements:
import re data_1 = ' 2,000/3,000 ' # Split on "/" with any amount of whitespace before/after data_2 = re.split(r'\s*/\s*', data_1.strip()) print(data_2) # Output: ['2,000', '3,000']
The \s* matches zero or more whitespace characters, and we call strip() on the original string first to get rid of any leading/trailing whitespace outside the split elements.
Method 3: Skip Regex Entirely (Since Your Separator is Simple)
If you're only splitting on a single / character, you don't even need regex—Python's built-in string split() method works just fine. Pair it with the same list comprehension trick:
data_1 = ' 2,000/3,000 ' data_2 = [item.strip() for item in data_1.split('/')] print(data_2) # Output: ['2,000', '3,000']
Quick Note on Your Previous Attempt
When you tried split(data2), that didn't work because split() is a method that belongs to strings, not lists. You need to apply it to each string inside the list, which is exactly what the list comprehension does.
内容的提问来源于stack exchange,提问作者sayditto

