Python中如何快速去除字符串首尾的特定符号(例如...text...)?

文稿中,有很多文字是用括号(...text...)框起来的,括号前面有 # 的那一行,类似这样:

#(...text...)

须要把 # 连()一起剥去,剩下:

...text...

没有 # 开头的那一行,括号(...text...)继续保留不动。


Python中如何快速去除字符串首尾的特定符号(例如...text...)?
21 回复

自己写一个解析器,快速跑一下。
不用解析的方法,可能会出错


def strip_specific_chars(text, chars):
    """
    去除字符串首尾指定的字符集合
    
    Args:
        text: 原始字符串
        chars: 要移除的字符集合(字符串形式)
    
    Returns:
        处理后的字符串
    """
    return text.strip(chars)

# 示例使用
original = "...Hello World!!!"
result = strip_specific_chars(original, ".!")
print(f"原始: '{original}'")
print(f"结果: '{result}'")
# 输出: 原始: '...Hello World!!!' → 结果: 'Hello World'

# 更灵活的正则表达式版本
import re

def strip_specific_pattern(text, pattern):
    """
    使用正则表达式去除首尾匹配模式的字符
    
    Args:
        text: 原始字符串
        pattern: 正则表达式模式
    
    Returns:
        处理后的字符串
    """
    return re.sub(f'^{pattern}+|{pattern}+$', '', text)

# 示例:去除首尾的点号
text_with_dots = "...some text..."
cleaned = strip_specific_pattern(text_with_dots, r'\.')
print(f"正则处理: '{cleaned}'")  # 输出: 'some text'

核心要点:

  • 简单情况用str.strip(chars)最快最直接
  • 复杂模式用正则表达式re.sub()更灵活
  • 注意strip()会移除字符集合中的所有字符,不是完整子串

一句话建议: 根据需求复杂度选择strip()或正则。

全文替换,正则表达式,比如说用 vscode

对 vim 来说 录制个宏,播放即可,估计也就几秒吧

sublime text 搜索#,选择所有,删除

审题失败,打扰了😷

任意一个支持正则的编辑器都能做到,楼主有尝试过吗?

随便一个支持正则的编辑器

应该是搜索#( 然后选择所有,删除,向右移动光标,删除)

尴尬😅,看到你发,我就不回了

notepad++正则替换 #((.*))替换为$1

text.lstrip(’#(’).ratio(’)’)

手机打字,手残了。。。
text.lstrip(’#(’).rstrip(’)’)

$ cat a
#(hello)world
#(he(llo)world
(hello)world

$ cat a | sed 's/^#((.*))/\1/'
helloworld
he(lloworld
(hello)world

上面的回复可能审题错误。

$ cat a
#hello(hello)world
#hello(he(llo)world
(hello)world

$ cat a | sed 's/^#(.)((.))/\1\2/'
hellohelloworld
hello(helloworld
(hello)world

解法同 13 楼,注意区分下中英文字符就行。好好学正则啊,非常有用

就算不用正则,用 Python 也就是一个 for 一个 if 的事………

1、vim 打开文件:%s/^#((.*))$/\1/

。。。ctrl + 回车不是换行。。。
1、用 vim 打开文件,然后进入命令模式,输入 %s/^#((.))$/\1/ 回车就好了

2、sed -i ‘.bak’ "s/^#((.
))$/\1/" <filename> ;
#上面的.bak 因为实在 Mac os 环境下才使用,其他的应该不需要

回到顶部