python怎么删除字符-Python教程

资源魔 27 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怎样删除了字符的具体内容,更多请存眷资源魔其它相干文章!

标签: Python python教程 python编程 python使用问题

抱歉,评论功能暂时关闭!