Python: string replacement--replace(), teaslate(), re.sub

One, replace()

replace() The method replaces old (old string) with new (new string) in the string. If the third parameter max is specified, the replacement will not exceed max times

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

style: 

a = 'Hello,world!'
print(a.replace('l','Q'))  # 把l换成Q 
print(a.replace('abcdefghi','0123456789'))  # 想把字符串中的a到i替换成0-9
print(a.replace('world','apple'))  # 把word替换为apple

 result:

HeQQo,worQd!
Hello,world!  # 很明显,第二个没有执行(或者说没有替换)
Hello,apple!

Reason: The replace()function can replace a single character in string, and can also replace consecutive characters, but it cannot generate a character replacement map

 

Two, translate()

translate()The function also comes with python. The difference with the replace() function is that a str.maketransfunction is used here to create a table. It can use various parameters, but requires three Argumentsstr.

maketrans ('', '', del)  

The first parameter is the character to be replaced, the second parameter is the character to be replaced, and the third parameter is the character to be deleted

use:

stu_name = "学生1"
stu_name.translate(str.maketrans('', '', digits)) 
print(stu_name)  # 输出: 学生
import string
a = 'Hello,world!'
remove = string.punctuation  # 返回所有标点符号
table = str.maketrans('abcdefgh','01234567',remove)
print(a.translate(table))  # 输出:H4lloworl3

 

Three, re.sub()

This is a function in the re library, and its prototype isre.sub(pattern, repl, string, count)

The first parameter is the parameter to be replaced by the regular expression, the second parameter is the replaced string, the third parameter is the input string, and the fourth parameter refers to the number of replacements. The default is 0, which means that every match is replaced.

example: 

import re
a = 'Hello,world! HaHa'
print(re.sub(r'[A-Z]', '8', a))  # 8ello,world! 8a8a
print(re.sub(r'[A-Z]', '8', a, 2)) # 8ello,world! 8aHa 替换前2个

 

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_38676276/article/details/107515545