1. 程式人生 > >python如何去除字串中不想要的字元

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++++       '
 
# 刪除兩邊空字元
print(s.strip())
 
# 刪除左邊空字元
print(s.rstrip())
 
# 刪除右邊空字元
print(s.lstrip())
 
# 刪除兩邊 - + 和空字元
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 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() 方法構造一個字典,每個Unicode 和音符作為鍵,對於的值全部為None
  然後使用unicodedata.normalize() 將原始輸入標準化為分解形式字元
  sys.maxunicode : 給出最大Unicode程式碼點的值的整數,即1114111(十六進位制的0x10FFFF)。
  unicodedata.combining:將分配給字元chr的規範組合類作為整數返回。 如果未定義組合類,則返回0。
'''
cmb_chrs = dict.fromkeys(cfor c in range(sys.maxunicode)if unicodedata.combining(chr(c)))#此部分建議拆分開來理解
b =unicodedata.normalize('NFD', a)
'''
   呼叫translate 函式刪除所有重音符
'''
print(b.translate(cmb_chrs))

 via:http://www.cnblogs.com/2bjiujiu/p/7257744.html