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()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/python3
  
s = ' -----abc123++++  '
  
# 刪除兩邊空字符
print (s.strip())
  
# 刪除左邊空字符
print (s.rstrip())
  
# 刪除右邊空字符
print (s.lstrip())
  
# 刪除兩邊 - + 和空字符
print (s.strip().strip( '-+' ))

刪除單個固定位置字符: 切片 + 拼接

1
2
3
4
5
6
#!/usr/bin/python3
  
s = 'abc:123'
# 字符串拼接方式去除冒號
new_s = s[: 3 ] + s[ 4 :]
print (new_s)

刪除任意位置字符同時刪除多種不同字符:replace(), re.sub()

1
2
3
4
5
6
7
8
9
10
11
#!/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()做映射

1
2
3
4
5
6
7
#!/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字符中音調

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/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(c for c in range (sys.maxunicode) if unicodedata.combining( chr (c))) #此部分建議拆分開來理解
b = unicodedata.normalize( 'NFD' , a)
'''
   調用translate 函數刪除所有重音符
'''
print (b.translate(cmb_chrs))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM