python字符串替换replace,Python字符串替换
发布日期:2021-06-24 14:05:32 浏览次数:2 分类:技术文章

本文共 1164 字,大约阅读时间需要 3 分钟。

Python字符串替换

Python字符串替换教程

Python replace()函数详解

定义

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

语法

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

参数

参数

描述

str

需要替换的原字符串。

old

将被替换的子字符串。

new

新字符串,用于替换 old 子字符串。

max

可选字符串, 替换不超过 max 次。

返回值

返回替换后的字符串。

案例

替换字符串

使用 replace() 函数,实现字符串全部替换

print("嗨客网(www.haicoder.net)")

# 使用 strip() 函数,去除字符串的指定字符

strHaicoder = 'I love python, and study python from haicoder!'

print("before replace strHaicoder =", strHaicoder)

strHaicoder = strHaicoder.replace("python", "Golang")

print("after replace strHaicoder =", strHaicoder)

程序运行后,控制台输出如下:

387726be24615db9c4a0c65e7e629895.png

首先,我们定义了一个字符串类型的

因为,我们没有指定第三个参数,即替换次数,因此,整个字符串中的所有的 “python” 被替换为了 “Golang”。

替换字符串

使用 replace() 函数,实现字符串全部替换

print("嗨客网(www.haicoder.net)")

# 使用 strip() 函数,去除字符串的指定字符

strHaicoder = 'I love python, and study python from haicoder!'

print("before replace strHaicoder =", strHaicoder)

strHaicoder = strHaicoder.replace("python", "Golang", 1)

print("after replace strHaicoder =", strHaicoder)

程序运行后,控制台输出如下:

2059fcbb3da325d197dc30fde5e5f691.png

这次,我们指定了 replace 函数的第三个参数,即,只替换一次,结果,我们发现,整个字符串中的 “python” 只被替换了一次。

Python字符串替换总结

在 Python 中,我们需要将一个字符串替换成另一个字符串,使用 replace 函数。Python replace() 函数语法:

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

转载地址:https://blog.csdn.net/weixin_33308985/article/details/116183527 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:python爬取网站实例,Python实现抓取网页并且解析的实例
下一篇:php苹果内购验证,苹果内购支付校验

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月01日 08时58分43秒