类别:Python / 日期:2019-12-02 / 浏览:99 / 评论:0
python怎样删除字符?
python去除字符串中不想要的字符:
题目:
过滤用户输入中前后过剩的空缺字符
‘ ++++abc123--- ‘
过滤某windows下编辑文本中的'\r':
‘hello world \r\n'
去掉文本中unicode组合字符,声调
"Zhào Qián Sūn Lǐ Zhōu Wú Zhèng Wáng"
引荐:《Python教程》
怎样处理以上题目?
去掉两头字符串: 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(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c))) #此部份发起拆分开来明白 b = unicodedata.normalize('NFD', a) ''' 挪用translate 函数删除一切重音符 ''' print(b.translate(cmb_chrs))
以上就是python怎样删除字符的细致内容,更多请关注ki4网别的相干文章!
发表评论 / 取消回复