Home >Backend Development >Python Tutorial >How to replace the content of a string in python

How to replace the content of a string in python

尚
Original
2019-06-27 13:23:1213523browse

How to replace the content of a string in python

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

replace() function syntax:

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

Parameters: old -- the substring to be replaced. new – new string, used to replace old substring. max -- optional string, replaced no more than max times.

Return value: Return the new string generated after replacing old (old string) in the string with new (new string). If the third parameter max is specified, the replacement will not exceed max times.

The following examples show how to use the replace() function:

Examples:

#!/usr/bin/python
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);

The output results of the above examples are as follows:

thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

More Python related For technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to replace the content of a string in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn