You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何去除re.split()结果列表元素的左右空白

Fixing Whitespace After Splitting Your String

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 12:19:06