如何在Python中删除所有前导和尾随标点符号?

Spa*_*ine 10 python strip punctuation

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

import string

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

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

print(new_s)
# Output
ABC79999
Run Code Online (Sandbox Code Playgroud)

如何在Python中删除所有前导和尾随标点符号?期望的结果'.$ABC-799-99,#''ABC-799-99'.

Pad*_*ham 14

你完全按照你在问题中提到的那样做,你只需要str.strip它.

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

print(s.strip(punctuation))
Run Code Online (Sandbox Code Playgroud)

输出:

 ABC-799-99
Run Code Online (Sandbox Code Playgroud)

str.strip可以删除多个字符.

如果你只想删除主要标点,你可以str.lstrip:

s.lstrip(punctuation)
Run Code Online (Sandbox Code Playgroud)

或者rstrip任何尾随标点符号:

 s.rstrip(punctuation)
Run Code Online (Sandbox Code Playgroud)