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

2024-06-04 8327阅读

「作者主页」:士别三日wyx

「作者简介」:CSDN top100、阿里云博客专家、华为云享专家、网络安全领域优质创作者

「推荐专栏」:小白零基础《Python入门到精通》

replace函数使用详解

  • 1、不改变原字符串
  • 2、指定替换次数
  • 3、转义符
  • 4、替换列表、元组、字典的元素
  • 5、连续替换

    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

        Python replace()函数使用详解,Python替换字符串 第1张

        或者 TypeError: integer argument expected,

        Python replace()函数使用详解,Python替换字符串 第2张

        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
        

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


    免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

    目录[+]