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

如何移除数据列中字符串连字符两侧的空格?

移除字符串连字符两侧空格(支持批量处理数据列)

单个字符串处理

用正则表达式精准匹配连字符-前后的任意数量空白字符,直接替换为无空格的连字符即可:

import re

def removespace(s):
    return re.sub(r'\s*-\s*', '-', s)

# 测试示例
str1 = "101 - purple cloths"
str1sp = removespace(str1)
print(str1sp)  # 输出: 101-purple cloths

批量处理数据列(以Pandas为例)

如果要对整个数据列执行操作,直接调用Pandas的str.replace方法,传入相同正则规则就能批量处理:

import pandas as pd

# 构造测试数据
df = pd.DataFrame({
    'desc': [
        "101 - purple cloths",
        "202 - blue shoes",
        "303-green hats",  # 原本无空格的内容保持不变
        "404  -  red socks"  # 前后多空格的场景也能处理
    ]
})

# 批量清洗列数据
df['cleaned_desc'] = df['desc'].str.replace(r'\s*-\s*', '-', regex=True)

print(df['cleaned_desc'])
# 输出结果:
# 0    101-purple cloths
# 1      202-blue shoes
# 2        303-green hats
# 3      404-red socks
# Name: cleaned_desc, dtype: object

正则规则说明:

  • \s*:匹配0个或多个空白字符(包括空格、制表符等)
  • 整个规则会匹配所有带前后空格(或无空格)的连字符,替换为紧连的-,不会影响字符串其他位置的空格。

内容的提问来源于stack exchange,提问作者Adelore Similoluwa Gloria

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:35:18