這篇文章主要為大家詳細介紹了python如何去除字串中不想要的字元,具有一定的參考價值,感興趣的小夥伴們可以參考一下
問題:
過濾使用者輸入中前後多餘的空白字元
‘ ++++abc123--- ‘
過濾某windows下編輯文本中的'\r':
‘hello world \r\n'
去掉文本中unicode組合字元,音調
"Zhào Qián Sūn Lǐ Zhōu Wú Zhèng Wáng"
如何解決以上問題?
去掉兩端字串: strip(), rstrip(),lstrip()
#!/usr/bin/python3 s = ' -----abc123++++ ' # 刪除兩邊Null 字元print(s.strip()) # 刪除左邊Null 字元print(s.rstrip()) # 刪除右邊Null 字元print(s.lstrip()) # 刪除兩邊 - + 和Null 字元print(s.strip().strip('-+'))
刪除單個固定位置字元: 切片 + 拼接
#!/usr/bin/python3 s = 'abc:123'# 字串拼接方式去除冒號new_s = s[:3] + s[4:]print(new_s)
刪除任意位置字元同時刪除多種不同字元: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))
同時刪除多種不同字元:translate() py3中為str.maketrans()做映射
#!/usr/bin/python3 s = 'abc123xyz'# a _> x, b_> y, c_> z,字元對應表加密print(str.maketrans('abcxyz', 'xyzabc'))# translate把其轉換成字串print(s.translate(str.maketrans('abcxyz', 'xyzabc')))
去掉unicode字元中音調
#!/usr/bin/python3 import sysimport unicodedatas = "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, \ra = s.translate(remap)''' 通過使用dict.fromkeys() 方法構造一個字典,每個Unicode 和音符作為鍵,對於的值全部為None 然後使用unicodedata.normalize() 將原始輸入標準化為分解形式字元 sys.maxunicode : 給出最大Unicode代碼點的值的整數,即1114111(十六進位的0x10FFFF)。 unicodedata.combining:將分配給字元chr的規範組合類別作為整數返回。 如果未定義組合類別,則返回0。'''cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c))) #此部分建議拆分開來理解b = unicodedata.normalize('NFD', a)''' 調用translate 函數刪除所有重音符'''print(b.translate(cmb_chrs))