python字符串處理,去掉不想要的字符

問題:
    過濾用戶輸入中前后多余的空白字符
      ‘ ++++abc123--- ‘
    過濾某windows下編輯文本中的'\r':
      ‘hello world \r\n'
    去掉文本中unicode組合字符,音調(diào)
      "Zhào Qián Sūn Lǐ Zhōu Wú Zhèng Wáng"

1.去掉兩端字符串: strip(), rstrip(),lstrip()
#!/usr/bin/python3
s = ' -----abc123++++  '
#刪除兩邊空字符
print(s.strip())
# 刪除左邊空字符
print(s.rstrip())
# 刪除右邊空字符
print(s.lstrip())
# 刪除兩邊 - + 和空字符
print(s.strip().strip('-+'))
print(s.strip('abc'))
2.刪除單個固定位置字符: 切片 + 拼接
#!/usr/bin/python3
s = 'abc:123'
# 字符串拼接方式去除冒號
new_s = s[:3] + s[4:]
print(new_s)
3.刪除任意位置字符同時刪除多種不同字符:replace(), re.sub()
#!/usr/bin/python3
# 去除字符串中相同的字符
s = '\tabc\t123\tisk'
print(s.replace('\t', ''))
import re
# 去除\r\n\t字符
s = '\r\nabc\t123\nxyz'
print(re.sub('[\r\n\t]', '', s))
4.同時刪除多種不同字符:translate() py3中為str.maketrans()做映射
#!/usr/bin/python3
s = 'abc123xyz'
# a _> x, b_> y, c_> z,字符映射加密
print(str.maketrans('abcxyz', 'xyzabc'))
# translate把其轉(zhuǎn)換成字符串
print(s.translate(str.maketrans('abcxyz', 'xyzabc')))
5.去掉unicode字符中音調(diào)
#!/usr/bin/python3
import sys
import unicodedata
s = "Zhào Qián Sūn Lǐ Zhōu Wú Zhèng Wáng"
remap = {
 # ord返回ascii值
 ord('\t'): '',
 ord('\f'): '',
 ord('\r'): None
 }

# 去除\t, \f, \r
a = s.translate(remap)
'''
  通過使用dict.fromkeys() 方法構(gòu)造一個字典,每個Unicode 和音符作為鍵,對于的值全部為None
  然后使用unicodedata.normalize() 將原始輸入標(biāo)準(zhǔn)化為分解形式字符
  sys.maxunicode : 給出最大Unicode代碼點(diǎn)的值的整數(shù),即1114111(十六進(jìn)制的0x10FFFF)。
  unicodedata.combining:將分配給字符chr的規(guī)范組合類作為整數(shù)返回。 如果未定義組合類,則返回0。
'''
cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c))) #此部分建議拆分開來理解
b = unicodedata.normalize('NFD', a)
'''
   調(diào)用translate 函數(shù)刪除所有重音符
'''
print(b.translate(cmb_chrs))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容