字符串删除指定符号(不限位置)

python中去掉字符串中某些不想要的字符:

1、一般的可以用replace()

  这个函数不限定位置,是可以替换原来不想要的字符,替换成空 字符就相当于删除了

2、也可以用strip(),删除两边的字符(默认是删除左右空格)

  rstrip(),lstrip()这两个可以选择只删除左边或者右边

3、re.sub

  这个可以根据正则删除,此处是删除串中的数字1-9,字符a-z,A-Z,还可以加其他的

import re

str="aksj2343ngr4545g黄金叶子fg"
temp = re.sub('[a-zA-Z1-9]','',str)
print(temp)

4、也可以用映射

  

from string import maketrans   # 必须调用 maketrans 函数。

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
#这里建立了一个映射
s = 'abc123def456ghi789zero0'
res = s.translate(trantab )
#这里使用映射把串中的aeiou转换为12345

猜你喜欢

转载自www.cnblogs.com/51python/p/11259486.html