本文目錄一覽:
python 去掉標點符號
這個明顯是錯誤的,你根本沒理解replace函數是怎麼用的。
Python str.replace(old, new[, max])
方法把字元串str中的 old(舊字元串) 替換成 new(新字元串),如果指定第三個參數max,則替換不超過 max
次。
如果非要用replace()函數來實現要這樣寫:
import string
m = l
for c in string.punctuation:
m = m.replace(c,”)
更簡便的方法是用translate(),代碼如下:
import string
m = l.translate(None, string.punctuation)
python中刪除字元串中的標點符號
string = ‘蘋果,apple。不是嗎?’
f = ‘,。?’
# f裡面擴充符號即可
for i in f:
string = string.replace(i, ”)
print(string)
python – 去除字元串中特定字元
一、去掉字元串兩端字元: strip(), rstrip(), lstrip()
s.strip() # 刪除兩邊(頭尾)空字元,默認是空字元
s.lstrip() # 刪除左邊頭部空字元
s.rstrip() # 刪除右邊尾部空字元
s.strip(‘+-‘) # 刪除兩邊(頭尾)加減字元
s.strip(‘-+’).strip() # 刪除兩邊(頭尾)加減和空字元
s.strip(‘x’) # 刪除兩邊特定字元,例如x
二、去掉字元串中間字元: replace(), re.sub()
# 去除\n字元
s = ‘123\n’
s.replace(‘\n’, ”)
import re
# 去除\r\n\t字元
s = ‘\r\nabc\t123\nxyz’
re.sub(‘[\r\n\t]’, ”, s)
三、轉換字元串中的字元:translate()
s = ‘abc123xyz’
# a – x, b – y, c – z,建立字元映射關係
str.maketrans(‘abcxyz’, ‘xyzabc’)
# translate把其轉換成字元串
print(s.translate(str.maketrans(‘abcxyz’, ‘xyzabc’)))
參考鏈接:
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/255165.html