Python3.x string replacement methods replace(), maketrans() and translate()

The replace() function in Python is similar to the "find and replace" function

The syntax format is as follows:

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

 

The method replaces the old (old string) in the string with new (new string). If the third parameter max is specified, the replacement will not exceed max times. Because the string is immutable, the result is returned For a new string, we need to save its result.

Example:

operation result:

Another string replacement method is a set of two paired string objects maketrans() and translate(). The maketrans() method is used to generate a string mapping table, and the translate() method is used to define the mapping table. The corresponding relationship between converts the string and replaces the characters in it. The combination of these two methods can handle multiple different characters at the same time, but the replace() method cannot meet this requirement.

Example:

 

operation result:

 

Guess you like

Origin blog.csdn.net/My_daily_life/article/details/108762827