本文目錄一覽:
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-hk/n/255165.html