2016-05-14 128 views
6

我知道如何刪除字符串中的所有標點符號。如何去除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'

+2

's.strip(string.punctuation) ' – zondo

+1

我搜索了你的問題標題,鏈接副本是第一個結果,你正在尋找確切的解決方案。請在未來做更多的研究。 – TigerhawkT3

+0

@ TigerhawkT3,thx,我研究過SO。 – SparkAndShine

回答

10

你確實在你的問題中提到了什麼,你只是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) 
+0

Thx。如果我保留'$','s.strip(string.punctuation.replace('$',''))',這是更好的方法嗎? – SparkAndShine

+1

@sparkandshine,不用擔心,我認爲'.punctuation.replace('$','')'很不錯,另一種選擇是手動創建一個標點符號字符串減去$並使用我認爲會很多更艱鉅。 –

相關問題