python字符串替换函数_Python3字符串替换replace(),translate(),re.sub()

Python3的字符串替换,这里总结了三个函数,replace()和translate()和re.sub()

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()函数,其用法更加多样化。比如,可以加入一个字典,用于替换对不同的值进行替换。

s = pd.Series([0, 1, 2, 3, 4])

s.replace({0:'a',1:'b'})

Out[2]:

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

string.punctuation返回所有的标点符号,更多字符串常量如下图:

1389398-20180515004443246-607463306.png

str.maketrans()的前两个参数相当于一个映射表,如上述结果,所有的'e'被替换成了'4'

第三个参数为要删除的字符,上述例子删除了所有的标点符号,如果要删除的字符还要加上空格的话,则可以这样:

table = str.maketrans('abcdefgh','01234567',remove+' ')

print(a.translate(table))

H4lloworl3By4By4

re.sub()

这个是re库里的函数,其原型为re.sub(pattern, repl, string, count)

第一个参数为正则表达式需要被替换的参数,第二个参数是替换后的字符串,第三个参数为输入的字符串,第四个参数指替换个数。默认为0,表示每个匹配项都替换。

import re

a = 'Hello,world. ByeBye!'

print(re.sub(r'[A-Z]', '8', a))

8ello,world. 8ye8ye!

上述例子是把所有的大写字母替换成8,下述表示只替换前2个这样的大写字母。

print(re.sub(r'[A-Z]', '8', a, 2))

8ello,world. 8yeBye!

Reference:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值