Python有一组可以用于字符串的内置方法。Python 字符串操作常用操作,如字符串的替换、删除、截取、赋值、连接、比较、查找、分割等。本文主要介绍Python 字符串 replace() 方法

Python 字符串方法

例如:

替换"bananas"一词:

txt = "I like bananas"

x = txt.replace("bananas", "apples")

print(x)

1、定义和用法

replace()方法将一个指定的字符串替换为另一个指定的字符串。

注意:如果未指定count参数,则将替换所有出现的指定字符串。

2、调用语法

string.replace(oldvalue, newvalue, count)

3、参数说明

参数

描述

oldvalue

必需的参数,要被替换的字符串

newvalue

必需的参数,将旧字符串要替换成的字符串

count

可选的。一个数字,指定想要执行替换的次数,

不指定默认替换所有出现的字符串

4、使用示例

例如:

替换所有出现的单词“one”:

txt = "one one was a race horse, two two was one too."

x = txt.replace("one", "three")

print(x)

例如:

替换单词“ one”的两个第一次出现:

txt = "one one was a race horse, two two was one too."

x = txt.replace("one", "three", 2)

print(x)

Python 字符串方法

推荐文档

相关文档

大家感兴趣的内容

随机列表