Python替换字符串replace()函数使用方法详解

 更新时间:2023年07月26日 10:39:52   作者:士别三日wyx  
Python中的replace()方法是把字符串中的old(旧字符串)替换成new(新字符串),如果指定第三个参数max,则替换次数不超过max次(将旧的字符串用心的字符串替换不超过max次,本文就给大家讲讲Python replace()函数的使用方法,需要的朋友可以参考下

replace() 可以「替换」字符串中的内容

语法

string.replace( old, new, count )

参数

  • old :(必选,字符串类型)被替换的字符串
  • new :(必选,字符串类型)替换后的字符串
  • count :(可选,整型)替换的次数

返回值

  • 返回替换后的新字符串

实例:将字符串中的 “hello” 替换成 “world”

str1 = 'hello hello hello hello world'
str2 = str1.replace('hello', 'world')
print(str2)

输出:

world world world world world

1、不改变原字符串

因为Python中的字符串是「不可变」的,所以 replace() 不会改变原字符串的内容,而是返回一个新的字符串。

我们分别打印替换前、后的两个字符串「内容」和「内存地址」。

str1 = 'hello hello hello hello world'
print(id(str1))
str2 = str1.replace('hello', 'world')
print(str1, id(str1))
print(str2, id(str2))

输出:

2834751121168
hello hello hello hello world 2834751121168
world world world world world 2834751121568

可以看到,原字符串的内容和内存地址没有发生变化。

2、指定替换次数

「不指定」次数,默认替换「所有」匹配到的字符串

str1 = 'hello_1 hello_2 hello_3 hello_4'
print(str1.replace('hello', 'world'))

输出:

world_1 world_2 world_3 world_4

替换次数为「正数」时,按照从左到右的顺序替换,设置几次就替换几次

str1 = 'hello_1 hello_2 hello_3 hello_4'
print(str1.replace('hello', 'world', 1))
print(str1.replace('hello', 'world', 3))

输出:

world_1 hello_2 hello_3 hello_4
world_1 world_2 world_3 hello_4

替换次数为「负数」时,无论负几,都会替换所有匹配到的内容

str1 = 'hello_1 hello_2 hello_3 hello_4'
print(str1.replace('hello', 'world', -1))
print(str1.replace('hello', 'world', -3))

输出:

world_1 world_2 world_3 world_4
world_1 world_2 world_3 world_4

指定的次数必须是「整型」,否则会报错 TypeError: ‘str’ object cannot be interpreted as an integer

或者 TypeError: integer argument expected,

3、转义符

字符串中的转义符不会打印出来,但 replace() 可以替换这些转义符,比如替换换行符\n

str1 = 'hello world\n'
print(str1)
print(str1.replace('\n', ' new'))

输出:

hello world
hello world new

从结果可以看到,替换前会换行,替换后不会换行,因为转义符被替换掉了。

4、替换列表、元组、字典的元素

对「列表」中的元素使用 replace() ,可以使用下面这种方式

arr = ['hello', 'hello', 'hello']
print([string.replace('hello', 'world') for string in arr])

输出:

['world', 'world', 'world']

这种方式本质上是生成了一个「新数组」,我们可以看一下内存地址

arr = ['hello', 'hello', 'hello']
print(id(arr))
print(id([string.replace('hello', 'world') for string in arr]))

输出:

1658941612416
1658941612544

或者使用「循环」的方式替换列表中的元素,这种方式不会生成新数组,替换前、后的内存地址是一样的。

arr1 = ['hello', 'hello', 'hello']
print(arr1, id(arr1))
for a in range(len(arr1)):
    arr1[a] = arr1[a].replace('hello', 'world')
print(arr1, id(arr1))

输出:

['hello', 'hello', 'hello'] 1672076599552
['world', 'world', 'world'] 1672076599552

替换「元祖」中的元素,需要先转成列表,再循环替换,替换完成再转回元组,这种方式同样会改变内存地址。

tu = ('hello', 'hello', 'hello')
print(id(tu))
arr1 = list(tu)
for a in range(len(arr1)):
    arr1[a] = arr1[a].replace('hello', 'world')
tu = tuple(arr1)
print(tu, id(tu))

输出:

2255689005696
('world', 'world', 'world') 2255689005824

替换「字典」的值,直接循环替换

dic = {'key1': 'zhangsan', 'key2': 'lisi'}
for a in dic:
    dic[a] = dic[a].replace('zhangsan', 'new')
print(dic)

输出:

{'key1': 'new', 'key2': 'lisi'}

5、连续替换

因为 replace() 返回的是一个字符串,所以我们可以对返回的结果再次replace(),比如下面这样:

str1 = 'zhangsan lisi wangwu'
print(str1.replace('zhangsan', 'new').replace('lisi', 'new'))

输出:

new new wangwu

有多个内容需要替换时,可以使用这种简化的方式。

到此这篇关于Python替换字符串replace()函数使用方法详解的文章就介绍到这了,更多相关Python replace()函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python DataFrame 设置输出不显示index(索引)值的方法

    Python DataFrame 设置输出不显示index(索引)值的方法

    今天小编就为大家分享一篇Python DataFrame 设置输出不显示index(索引)值的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-06-06
  • 用python写个颜值评分器筛选最美主播

    用python写个颜值评分器筛选最美主播

    这篇文章主要介绍了我如何用python写颜值评分器,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-08-08
  • 详解Python中魔法方法的使用

    详解Python中魔法方法的使用

    Python的魔法方法,也称为dunder(双下划线)方法,是可以让你对类添加“魔法”的特殊方法。本文主要来和大家聊聊魔法方法的使用,需要的可以参考一下
    2022-12-12
  • Python搭建NLP模型的步骤和代码详解

    Python搭建NLP模型的步骤和代码详解

    这篇文章主要为大家详细介绍了Python搭建NLP模型的详细步骤,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以跟随小编一起学习一下
    2025-03-03
  • Python实现API开发的详细教程

    Python实现API开发的详细教程

    在现代软件开发中,API扮演着至关重要的角色,API接口用于不同软件组件之间的通信和数据交换,实现了系统之间的互操作性,Python作为一种简单易用且功能强大的编程语言,广泛应用于API接口的开发,本文将详细介绍如何使用Python开发API接口,需要的朋友可以参考下
    2024-12-12
  • python实现模拟按键,自动翻页看u17漫画

    python实现模拟按键,自动翻页看u17漫画

    这篇文章主要介绍了python实现模拟按键,自动翻页看u17漫画,十分简单实用,需要的朋友可以参考下
    2015-03-03
  • TensorFlow索引与切片的实现方法

    TensorFlow索引与切片的实现方法

    这篇文章主要介绍了TensorFlow索引与切片的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • python中文编码问题小结

    python中文编码问题小结

    这篇文章主要介绍了python中文编码问题,是Python程序设计中比较常见的一类问题,本文以实例形式对此进行了较为详细的总结,需要的朋友可以参考下
    2014-09-09
  • Python自动化管理文件的6个实用脚本总结

    Python自动化管理文件的6个实用脚本总结

    在日常工作中,手动管理文件既耗时又容易出错,而Python提供了强大的工具来自动完成这些任务,本文为大家整理了6个Python自动化管理文件的实用脚本,希望对大家有所帮助
    2026-03-03
  • python flask框架实现重定向功能示例

    python flask框架实现重定向功能示例

    这篇文章主要介绍了python flask框架实现重定向功能,结合实例形式分析了flask框架重定向功能的实现与使用方法,需要的朋友可以参考下
    2019-07-07

最新评论