2 回答
TA貢獻1824條經驗 獲得超8個贊
那是因為您從第一行的方法返回,在return text.replace(" ",''). 將其更改為text = text.replace(" ", ""),它應該可以正常工作。
此外,縮進可能在您的帖子中搞砸了,可能是在復制粘貼期間。
完整的方法片段:
def remove_punctuation(text):
text = text.replace(" ",'')
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)
TA貢獻1810條經驗 獲得超5個贊
您可以使用str以下方法刪除不需要的字符:
import string
tr = ''.maketrans('','',' '+string.punctuation)
def remove_punctuation(text):
return text.translate(tr)
txt = 'Point.Space Question?'
output = remove_punctuation(txt)
print(output)
輸出:
PointSpaceQuestion
maketrans創建替換表,它接受 3 str-s:第一個和第二個必須等長,第一個的第 n 個字符將替換為第二個的第 n 個字符,第三個str是要刪除的字符。您只需要刪除(而不是替換)字符,因此前兩個參數是空str的。
添加回答
舉報
