如何去掉字符串中不需要的字符

作者: SmallRookie | 来源:发表于2017-08-10 10:00 被阅读87次
实际案例
  1. 过滤掉用户输入中前后多余的空白字符:"  hello  "
  2. 过滤某Windows系统下某编辑文件应用在编辑文本时插入的"\r"

解决方案:

  • 方法一:字符串strip(),lstrip()和rstrip()方法去掉字符串两端,左边和右边的字符;
  • 方法二:删除单个固定位置的字符,可以使用切片+拼接的方式;
  • 方法三:字符串的replace()方法或正则表达式re.sub()删除任意位置字符。
# -*- coding: utf-8 -*-

import re

s1 = "     hello    "
# 方法一
print s1.strip()

s2 = "hello\r\n"

# 方法二
print s2[:-2]

# 方法三,replace()
print s2.replace("\r", "")

# 方法三,sub.re()
print re.sub("[\r]", "", s2)

运行结果为:

hello
hello
hello

hello

注:本文实际案例中有一特殊案例,本人在Windows系统和Linux系统下都未成功解决,希望阅读此文的大佬能帮忙解惑,谢谢!

问题为如何去除Unicode中组合字符(音调):'zhào'。

查阅相关教程得知此问题宜采用translate()方法,其代码如下:

u = u'zhào'

print u.translate({0xe0:None})

其输出结果为:

zho

输出结果中‘zhào’的‘à’去除了,但我们本意是去除‘a’的音调。除此之外,本方法有个问题就是需要事先知道Unicode中组合字符的ASCII。对于这个问题,我们可在shell下得知,但若在Python 3.X版本中就无法通过shell得知。

根据北门吹雪(O(∩_∩)O谢谢)的博客可得到Python 3.X版本的解决办法,其代码如下:

import sys
import unicodedata

u = "Zhào"

'''
  通过使用dict.fromkeys() 方法构造一个字典,每个Unicode和音调作为键,对于的值全部为None
  然后使用unicodedata.normalize() 将原始输入标准化为分解形式字符
  sys.maxunicode : 给出最大Unicode代码点的值的整数,即1114111(十六进制的0x10FFFF)。
  unicodedata.combining:将分配给字符chr的规范组合类作为整数返回。 如果未定义组合类,则返回0。
'''
s = unicodedata.normalize('NFD', u)
cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c)))
'''
   调用translate 函数删除所有音调
'''
print(s.translate(cmb_chrs))

运行结果为:

Zhao

Python 2.X的版本的代码如下:

import sys
import unicodedata

u = u'zhào'

s = unicodedata.normalize('NFD', u)
cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(unichr(c)))

print s.translate(cmb_chrs)

运行结果与Python 3.X版本的结果一致。

相关文章

网友评论

    本文标题:如何去掉字符串中不需要的字符

    本文链接:https://www.haomeiwen.com/subject/cudxrxtx.html