python替换文本中首尾的标点符号
时间: 2024-05-02 21:17:26 浏览: 100
可以使用正则表达式和字符串的 `strip()` 方法来实现。
以下是一个例子:
```python
import re
text = "Hello, world! This is a text. "
# 定义需要去除的标点符号
punctuation = '[!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]'
# 使用正则表达式去除首尾标点符号
text = re.sub('^'+punctuation+'+|'+punctuation+'+$', '', text)
# 使用字符串的 strip() 方法去除首尾空格
text = text.strip()
print(text)
```
输出结果:
```
Hello, world! This is a text
```
其中,正则表达式 `'^'+punctuation+'+|'+punctuation+'+$'` 匹配了文本开头或结尾的至少一个标点符号,并使用 `re.sub()` 方法将其替换为空字符串。然后使用字符串的 `strip()` 方法去除首尾空格。
阅读全文
相关推荐


















