Python3 replace()方法

Python 3 教程 · 2019-02-06 07:28:28

描述

replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

语法

replace()方法语法:

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

参数

  • old -- 将被替换的子字符串。
  • new -- 新字符串,用于替换old子字符串。
  • max -- 可选字符串, 替换不超过 max 次

返回值

返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

实例

以下实例展示了replace()函数的使用方法:

#!/usr/bin/python3

str = "www.w3cschool.cc"
print ("码农教程旧地址:", str)
print ("码农教程新地址:", str.replace("w3cschool.cc", "codercto.com"))

str = "this is string example....wow!!!"
print (str.replace("is", "was", 3))

以上实例输出结果如下:

码农教程旧地址: www.w3cschool.cc
码农教程新地址: www.codercto.com
thwas was string example....wow!!!

点击查看所有 Python 3 教程 文章: https://codercto.com/courses/l/10.html

查看所有标签

The Tangled Web

The Tangled Web

Michal Zalewski / No Starch Press / 2011-11-26 / USD 49.95

"Thorough and comprehensive coverage from one of the foremost experts in browser security." -Tavis Ormandy, Google Inc. Modern web applications are built on a tangle of technologies that have been de......一起来看看 《The Tangled Web》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具