Python3 's string substitution, here is a summary of three functions, and a replace()
translate()
re.sub()
Replace ()
replace()
Method replaces the old (older string) in the string with the new one, and if you specify the third parameter max, the replacement does not exceed Max times
str.replace(old, new[, max])
=‘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!
Visible, replace()
a function can replace a single character in a string, or it can replace consecutive characters, but cannot generate a character substitution mapping table
Translate ()
translate()
The function is also Python-brought. Unlike the replace () function, where str.maketrans
a function is used to create a table, it can use a variety of parameters, but requires three arguments.
str.maketrans(‘‘,‘‘,del)
The first parameter is the substituted character, the second argument is the substituted character, and the third argument is the character to be deleted
import=‘Hello,world. ByeBye!‘==str.maketrans(‘abcdefgh‘,‘01234567‘,remove)print(a.translate(table))
H4lloworl3 By4By4
string.punctuation
Returns all punctuation, more string constants such as:
str.maketrans()
The first two parameters are equivalent to a mapping table, such as the above results, all ‘e‘
are replaced by the‘4‘
The third parameter is the character you want to delete, the above example removes all punctuation, and if you want to remove the character with a space, you can:
=str.maketrans(‘abcdefgh‘,‘01234567‘,remove+‘ ‘)print(a.translate(table))
H4lloworl3By4By4
Re.sub ()
This is the function in the RE library, and its prototype isre.sub(pattern, repl, string, count)
The first parameter is the parameter that the regular expression needs to be replaced, the second argument is the replaced string , the third argument is the input string, and the fourth parameter refers to the number of replacements. The default is 0, which means that each match is replaced.
import=‘Hello,world. ByeBye!‘print(re.sub(r‘[A-Z]‘‘8‘, a))
8ello,world. 8ye8ye!
The above example is to replace all uppercase letters with 8, the following means only replace the first 2 such uppercase letters.
print(re.sub(r‘[A-Z]‘‘8‘2))
8ello,world. 8yeBye!
- Python3 Replace () method
- Nlp-python3 translate () error problem-typeerror:translate () takes exactly one argument (2 given
- Python Standard library Note: string module
- About the re.sub usage of Python
Python3 string Replace replace (), translate (), re.sub ()