在Python中用replace()函数操作指定字符

常用字符unicode的编码范围:

数字:\u0030-\u0039

汉字:\u4e00-\u9fa5

大写字母:\u0041-\u005a

小写字母:\u0061-\u007a

英文字母:\u0041-\u007a

1、将字符串中的指定符号替换成指定符号

#将old字符串中的2替换为9
old = "bcsbviuwvb123221iuw"
new = old .replace('2', '9')

2、字符串删掉空格 str.strip():

str.strip(): 删除开头和结尾的空格
str.lstrip(): 删除开头(左侧)的空格
str.rstrip(): 删除结尾(右侧)的空格
str.replace(’ ', ‘’):删除字符串中的所有空格

3、字符串删掉除汉字以外的所有字符

import re
old= "djsnfiosnhi1u2874834"
new = re.sub('([^\u4e00-\u9fa5])', '', old)
print(new) 

4、字符串删掉除汉字和数字以外的其他字符

import re
old= "djsnfiosnhi1u2874834"
new = re.sub('([^\u4e00-\u9fa5\u0030-\u0039])', '', old)
print(new)```