zoukankan      html  css  js  c++  java
  • 01-Python里字符串的常用操作方法--replace()函数

    1. replace()  函数

    作用: 替换字符串

    语法: replace('需要替换的子串', '新的子串', '替换的次数(可不传)') # 当替换次数不传时,默认全部替换

    实例一:

    mystr = 'you and me and he'
    new_str1 = mystr.replace('and', 'or')  #没传替换次数,则会把字符串中的所有and子串都替换成or
    print(new_str1)

    结果:  

    实例二:

    mystr = 'you and me and he'
    new_str2 = mystr.replace('and', 'or', 1)  # 传了替换次数1,则只会将字符串中的第一个and替换成or
    print(new_str2)

    结果: 

    实例三:

    mystr = 'you and me and he'
    new_str3 = mystr.replace('and', 'or', 10)    # 替换次数如果超出子串出现的次数,表示替换所有这个子串
    print(new_str3)

    结果: 

    注意:

    1.调用replace函数后,发现原有字符串的数据并未修改,修改后的数据是replace函数的返回值

    2.说明字符串是不可变数据类型

    3.数据是否可以改变划分为 可变类型 和不可变类型,而字符串属于不可变类型的数据类型

  • 相关阅读:
    Java异常面试题
    Quickhit快速击键
    多态and接口
    Java面向对象编程概述
    学生管理系统--分层开发
    类型转换
    文件上传
    ongl(示例3-6 多值类型的数据处理)
    ongl(原始类型和包装类型)
    Interceptor
  • 原文地址:https://www.cnblogs.com/zack-dong/p/14040254.html
Copyright © 2011-2022 走看看