python 正则之提取字符串中的汉字,数字,字母

版权声明:本文为博主原创文章,欢迎交流分享,未经博主允许不得转载。 https://blog.csdn.net/HHTNAN/article/details/82662885
#\d 匹配一个数字字符。等价于 [0-9]
#\D 匹配一个非数字字符。等价于 [^0-9]

#过滤字符串中的英文与符号,保留汉字
import re
st = "hello,world!!%[545]你好234世界。。。"
ste = re.sub("[A-Za-z0-9\!\%\[\]\,\。]", "", st)
print(ste)

#从字符串中提取数字
totalCount = '100abc'
totalCount = re.sub("\D", "", totalCount) 
print(totalCount)

#从字符串中提取字母字符串
import re
st = "hello,world!!%[545]你好234世界。。。"
result = ''.join(re.findall(r'[A-Za-z]', st)) 
print(result)
你好世界
100
helloworld

python3 去除字符串中的数字

python3:

from string import digits

s = 'abc123def456ghi789zero0'
remove_digits = str.maketrans('', '', digits)
res = s.translate(remove_digits)
# 'abcdefghizero'

或者:

filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h")

还可以:

for i in range(10):
  a.replace(str(i),'')

python2:

from string import digits

s = 'abc123def456ghi789zero0'
res = s.translate(None, digits)
# 'abcdefghizero'

猜你喜欢

转载自blog.csdn.net/HHTNAN/article/details/82662885