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返回所有的标点符号,更多字符串常量如下图:

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

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

table = str.maketrans('abcdefgh',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]',a,2))
8ello,world. 8yeBye!

 

 

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...