python中字符串替换方式

第一种--replace()函数接收两个参数,第一个参数为要被替换的子字符串,第二个参数为替换后的新字符串

string = "张三180"
new_string1 = string.replace(string, "李四")  # >>> 李四
new_string2 = string.replace('张三', "李四")  #  >>> 李四180
print(new_string1)
print(new_string2)

第二种--Template

string = "${name} is a ${age}"
t = Template(string)
print(t.substitute(name="张三", age="18"))  # >>>   张三 is a 18
# 变量没与字典匹配的话,解释器会抛出KeyError
print(t.substitute(name="张三"))  # >>> KeyError: 'age'
print(t.safe_substitute({"name": "张三", "age": "18"}))  # >>>  张三 is a 18
# 没有匹配则不会被替代
print(t.safe_substitute({"name": "张三"}))  # >>> 张三 is a ${age}

相关推荐

  1. python字符串替换方式

    2024-01-09 14:04:01       57 阅读
  2. Python——用新字符替换字符串的旧字符

    2024-01-09 14:04:01       37 阅读
  3. Python 利用string.Template完成字符串替换

    2024-01-09 14:04:01       46 阅读
  4. m4_python字符串-切割与替换

    2024-01-09 14:04:01       25 阅读
  5. MySQL如何将字符串替换

    2024-01-09 14:04:01       56 阅读
  6. Python 3 如何使用 format 方法格式化字符串

    2024-01-09 14:04:01       54 阅读
  7. python的replace替换函数

    2024-01-09 14:04:01       30 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-09 14:04:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-09 14:04:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-09 14:04:01       87 阅读
  4. Python语言-面向对象

    2024-01-09 14:04:01       96 阅读

热门阅读

  1. SpringBoot 静态资源映射

    2024-01-09 14:04:01       65 阅读
  2. How to keep a conversation going in English?

    2024-01-09 14:04:01       48 阅读
  3. 复试 || 就业day12(2024.01.08)算法篇

    2024-01-09 14:04:01       68 阅读
  4. spring aop

    2024-01-09 14:04:01       64 阅读
  5. Docker 中使用超级用户

    2024-01-09 14:04:01       61 阅读
  6. docker+cassandra

    2024-01-09 14:04:01       64 阅读
  7. How to view the high-tech zone atmospheric project

    2024-01-09 14:04:01       59 阅读
  8. RTTI(运行时类型识别)

    2024-01-09 14:04:01       51 阅读
  9. SpringBoot:泛型对象存取与转换<JedisPool>

    2024-01-09 14:04:01       61 阅读
  10. MySQL5.7 InnoDB 磁盘结构之Table

    2024-01-09 14:04:01       55 阅读
  11. setattr()函数的理解

    2024-01-09 14:04:01       64 阅读
  12. uni-app顶部导航条固定

    2024-01-09 14:04:01       67 阅读
  13. uni-app的优缺点?

    2024-01-09 14:04:01       49 阅读
  14. golang指针介绍

    2024-01-09 14:04:01       60 阅读
  15. Golang 协程与通道

    2024-01-09 14:04:01       63 阅读
  16. 计算机视觉(CV)技术

    2024-01-09 14:04:01       46 阅读