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

Python如何删除字符串首尾标点符号且保留中间的标点

实现方案

以下为不同常用开发语言的实现方案:

Python 实现

方法1:正则表达式(推荐,适配全量标点)

利用Unicode标点属性自动匹配所有首尾标点,无需手动维护标点集合:

import re

def trim_punctuation(s: str) -> str:
    # ^[\p{P}]+ 匹配开头所有标点,[\p{P}]+$ 匹配结尾所有标点
    return re.sub(r'^[\p{P}]+|[\p{P}]+$', '', s, flags=re.UNICODE)

# 测试
input_list = [':Hamburger{', 'word>', 'don´t', 'isn´t,']
output_list = [trim_punctuation(item) for item in input_list]
print(output_list) # 输出:['Hamburger', 'word', 'don´t', 'isn´t']

方法2:字符串strip方法(性能更优,适合标点集合固定场景)

手动指定要去除的标点集合,无需引入正则模块:

import string

# 可按需扩展标点集合,这里默认包含Python内置标点+示例中的大括号
punctuation_set = string.punctuation + '{}'

input_list = [':Hamburger{', 'word>', 'don´t', 'isn´t,']
output_list = [item.strip(punctuation_set) for item in input_list]
print(output_list) # 输出和正则方法一致

JavaScript 实现

function trimPunctuation(s) {
    // 匹配开头/结尾的非字母数字字符,u标记开启Unicode属性支持
    return s.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');
}

// 测试
const inputList = [':Hamburger{', 'word>', 'don´t', 'isn´t,'];
const outputList = inputList.map(item => trimPunctuation(item));
console.log(outputList); // 输出:['Hamburger', 'word', 'don´t', 'isn´t']

自定义调整说明

如果需要保留部分首尾标点,只需要修改正则中的匹配规则或者strip传入的标点集合即可,比如要保留首尾的单引号,将单引号从标点集合中移除即可。

内容的提问来源于stack exchange,提问作者Tacos al pastor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:45:06