Python3字符串和符号替换replace(),translate(),re.sub(), strip(), rstrip(),lstrip()

replace()

  • python 中的 replace() 方法把字符串中的 old(旧字符串) 替换成
    new(新字符串),如果指定第三个参数max,则替换不超过 max 次

str.replace(old, new[, max])

a = 'Hello,world. ByeBye!'
print(a.replace('l','Q'))
print(a.replace('abcdefghi','0123456789'))
print(a.replace('world','apple'))
HeQQo,worQd. ByeBye!
Hello,world. ByeBye!
Hello,apple. ByeBye!
  • 可见,replace()函数可以替换string中的单个字符,也可以替换连续的字符,但无法生成字符替换映射表
  • pandas 里面也有一个replace()函数,其用法更加多样化。比如,可以加入一个字典,用于替换对不同的值进行替换。
import pandas as pd
s = pd.Series([0, 1, 2, 3, 4])
print(s.replace({0:'a',1:'b'})) 
0    a
1    b
2    2
3    3
4    4
dtype: object

translate()

  • translate()函数也是python自带。与replace()
    函数不同的是,这里使用str.maketrans函数来创建一个表,它可以使用各种参数,但是需要三个Arguments。
str.maketrans('','',del)
  • 第一个参数为被替换的字符,第二个参数为替换的字符,第三个参数为要删除的字符
import string
a = 'Hello,world. ByeBye!'
remove = string.punctuation
table = str.maketrans('abcdefgh','01234567',remove)
print(a.translate(table))
结果:H4lloworl3 By4By4

strip(), rstrip(),lstrip()

#!/usr/bin/python3
  
s = '  +hello world-  '
  
# 删除两边空字符
print(s.strip())
结果:"+hello world-"

# 删除左边空字符
print(s.rstrip())
结果:"+hello world-  "

# 删除右边空字符
print(s.lstrip())
结果:"  +hello world-" 

# 删除两边 - + 和空字符
print(s.strip().strip('-+'))
结果:"hello world"

删除单个固定位置字符: 切片 + 拼接
s = 'abc:123'
# 字符串拼接方式去除冒号
new_s = s[:3] + s[4:]
print(new_s)
结果:abc123

re.sub()

re.sub(pattern, repl, string, count=0, flags=0)

函数参数:
pattern:正则中的模式字符串;
repl :替换的字符串,也可为一个函数;
string :要被查找替换的原始字符串;
count :模式匹配后替换的最大次数,默认 0 表示替换所有的匹配;

  • 例子是把所有的大写字母替换成8,下述表示只替换前2个这样的大写字母。
import re
a = 'Hello,world. ByeBye!'
print(re.sub(r'[A-Z]', '8', a))
结果: 8ello,world. 8ye8ye!

#删除任意位置字符同时删除多种不同字符:replace(), re.sub()
# 去除字符串中相同的字符
s = '\tabc\t123\tisk'
print(s.replace('\t', '')) 
  
import re
# 去除\r\n\t字符
s = '\r\nabc\t123\nxyz'
print(re.sub('[\r\n\t]', '', s))

#同时删除多种不同字符:translate()        
#py3中为str.maketrans()做映射
#!/usr/bin/python3

s = 'abc123xyz'
# a _> x, b_> y, c_> z,字符映射加密
print(str.maketrans('abcxyz', 'xyzabc'))
# translate把其转换成字符串
print(s.translate(str.maketrans('abcxyz', 'xyzabc')))


#去除数字,特殊字符,只保留汉字
import re
  
s = '1123*#$ 中abc国'
str = re.sub('[a-zA-Z0-9'!"#$%&\'()*+,-./:;<=>?@,。?★、…【】《》?“”‘'![\\]^_`{|}~\s]+', "", s)
# 去除不可见字符
str = re.sub('[\001\002\003\004\005\006\007\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a]+', '', x)
print(str)
# 结果为:中国

#去除特殊字符,只保留汉子,字母、数字
import re
string = "123我123456abcdefgABCVDFF?/ ,。,.:;:''';'''[]{}()()《》"
print(string)
123我123456abcdefgABCVDFF?/ ,。,.:;:''';'''[]{}()()《》
sub_str = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])","",string)
print(sub_str)
123我123456abcdefgABCVDFF

#去除[]括号
string = "[["中国", "北京"]]"
sub_str = re.sub('[\\]', '', string)
print(sub_str)
"中国", "北京"

正则表达式说明

函数说明
sub(pattern,repl,string)把字符串中的所有匹配表达式pattern中的地方替换成repl
[^**]表示不匹配此字符集中的任何一个字符
\u4e00-\u9fa5汉字的unicode范围
\u0030-\u0039数字的unicode范围
\u0041-\u005a大写字母unicode范围
\u0061-\u007a小写字母unicode范围
\uAC00-\uD7AF韩文的unicode范围
\u3040-\u31FF日文的unicode范围
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值