freeCodeCamp/guide/chinese/python/string-methods/string-replace-method/index.md

897 B

title localeTitle
String Replace Method 字符串替换方法

字符串替换方法

str.replace(old, new, max)方法用于将字符串old替换为字符串new ,总计max次数。此方法返回带有替换的字符串的新副本。原始字符串str保持不变。

例子

  1. "WAS"替换所有出现的"is" "WAS"
string = "This is nice. This is good." 
 newString = string.replace("is","WAS") 
 print(newString) 

产量

ThWAS WAS nice. ThWAS WAS good. 
  1. "WAS"替换前两次出现的"is" "WAS"
string = "This is nice. This is good." 
 newString = string.replace("is","WAS", 2) 
 print(newString) 

产量

ThWAS WAS nice. This is good. 

更多信息:

阅读Python文档中有关字符串替换的更多信息