python如何去除字串中不想要的字元

來源:互聯網
上載者:User
這篇文章主要為大家詳細介紹了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))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.