python 4-6 如何去掉字符串中不需要的字符strip'

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 4-6 如何去掉字符串中不需要的字符strip'相关的知识,希望对你有一定的参考价值。

方法一,字符串strip() lstrip() rstrip() 去掉字符串两端字符
方法二,删除单个位置的字符,可以使用切片 + 拼接的方式
方法三,字符串的replace()方法或者正则表达式re.sub删除任意位置字符
方法四,字符串translate方法,可以同时删除多种不同的字符
参考技术A 举头望明月,低头思故乡.

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

需求:
1、过滤用户输入中前后多余的空白字符
‘ nick2008@email.com ‘
2、过滤某windows下编辑文本中的‘ ‘:
‘hello world ‘
3、去掉文本中的unicode组合符号(音调):
tiān xià dì yī
思路:
1、字符串strip(),lstrip(),rstrip()方法去掉字符串两端字符
2、删除单个固定位置字符,可以使用切片+拼接的方式
3、字符串的replace()方法或者正则表达式re.sub()删除任意位置字符
4、字符串的translat()方法,可以同时删除多种不同字符

代码:

s1 = ‘   nick2008@email.com   ‘
s2 = ‘---abc+++‘
# strip()去除字符串首尾两端的字符,默认为空白字符。
print(s1.strip())
print(s2.strip(‘-+‘))

s3 = ‘abc:123‘
#删除字符串中的:
print(s3[:3]+s3[4:])

s4 = ‘	abc	123	xyz‘
#删除字符串的	
print(s4.replace(‘	‘,‘‘))

s5 = ‘	abc	123	xyz
opq
‘

# 去除字符串中的	
import re

ret = re.sub(‘[	
]‘,‘‘,s5)

print(ret)

s6 = ‘abc1230323xyz‘

#将字符串的a-->x,b-->y,c-->z,x-->a,y-->b,z-->a
# 生成映射表
table = str.maketrans(‘abcxyz‘,‘xyzabc‘)

# 使用translate的方法,完成这个映射的功能
ret2 = s6.translate(table)
print(ret2)

s7 = ‘tiān xià dì yī‘
# 去除字符串的音调
import sys
import unicodedata
remp = {
# ord返回ascii值
ord(‘	‘): ‘‘,
ord(‘f‘): ‘‘,
ord(‘
‘): None
}
# 去除	,f,
s7.translate(remp)
‘‘‘
通过使用dict.fromkeys()方法构造一个字典,每个unicode和音符作为键,对应的值全部为None,
然后使用unicodedata.normalize()将原始输入标准化为分解形式字符
sys.maxunicode:给出最大Unicode代码的值的整数,即1114111(十六进制的0x10FFFF).
unocodedata.combining:将分配给字符chr的规范组合类作为整数返回,如果未定义组合类,则返回0.
‘‘‘
cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c)))
b = unicodedata.normalize(‘NFD‘,s7)
#调用chraslate函数删除所有重音符
print(b.translate(cmb_chrs))

#方法2:
print(unicodedata.normalize(‘NFKD‘,s7).encode(‘ascii‘,‘ignore‘).decode())











以上是关于python 4-6 如何去掉字符串中不需要的字符strip'的主要内容,如果未能解决你的问题,请参考以下文章

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

17如何对字符串进行左, 右, 居中对齐 18如何去掉字符串中不需要的字符 19如何读写文本文件 20如何处理二进制文件 21如何设置文件的缓冲

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

python_如何去除字符串中不想要的字符?

python3 如何去除字符串中不想要的字符

python如何去掉字符串中的斜杠