如何去除Python中的所有前导和尾随标点?

2024-05-16 06:45:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何删除字符串中的所有标点符号。

import string

s = '.$ABC-799-99,#'

table = string.maketrans("","") # to remove punctuation
new_s = s.translate(table, string.punctuation)

print(new_s)
# Output
ABC79999

如何去除Python中的所有前导和尾随标点?'.$ABC-799-99,#'的理想结果是'ABC-799-99'


Tags: to字符串importnewoutputstringtableremove
1条回答
网友
1楼 · 发布于 2024-05-16 06:45:37

你做的正是你在问题中提到的,你只是str.strip而已。

from string import punctuation
s = '.$ABC-799-99,#'

print(s.strip(punctuation))

输出:

 ABC-799-99

str.strip可能需要删除多个字符。

如果您只想删除前导标点,可以str.lstrip

s.lstrip(punctuation)

rstrip任何尾随标点:

 s.rstrip(punctuation)

相关问题 更多 >