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

2022-10-04 20:21:27 字數 1969 閱讀 3959

問題:

過濾使用者輸入中前後多餘的空白字元

『    ++++abc123---   程式設計客棧; 『

過濾某windows下編www.cppcns.com輯文字中的'\r':

『hello world \r\n'

去掉文字中unicode組合字元,音調

"zho qin sn l zhu w zhng wng"

如何解決以上問題?

去掉兩端字串: strip(), rstrip(),lstrip()

#!/usr/bin/python3

s = ' -----abc123++++ '

# 刪除兩邊空字元

print(s.strip())

# 刪除左邊空字元

print(s.rstrip())

# 刪除右邊空字元

print(s.lstrip())

# 刪除兩邊 - + 和空字元

print(s.strip().strip('www.cppcns.com-+'))

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

#!/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 = "zho qin sn l zhu w zhng wng"

remap =

# 去除\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.combiningwww.cppcns.com(chr(c))) #此部分建議拆分開來理解

b = unicodedata.normalize('nfd', a)

'''   呼叫translate 函式刪除所有重音符

'''print(b.translate(cmb_chrs))

本文標題: 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 lst...

去除字串中重複字元

設計演算法並寫出 移除字串中重複的字元,不能使用額外的快取空間。注意 可以使用額外的乙個或兩個變數,但不允許額外再開乙個陣列拷貝。進一步地,為你的程式寫測試用例。這道題目其實是要你就地 in place 將字串中重複字元移除。你可以向面試官問清楚,不能使用額外的乙份陣列拷貝是指根本就不允許開乙個陣列...

如何用js去除字串空格,JS去除字串空格

方法一 使用replace正則匹配的方法 去除所有空格 str str.replace s g,去除兩頭空格 str str.replace s s g,去除左空格 str str.replace s 去除右空格 str str.replace s g,str為要去除空格的字串,例項如下 var s...