加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用字符串数组替换字符串

发布时间:2020-12-20 12:24:06 所属栏目:Python 来源:网络整理
导读:假设我有一个字符串s s = "?,?,test4,test5" 我知道有三个问号,我想用下面的数组相应地替换每个问号 replace_array = ['test1','test2','test3'] 获得 output = "test1,test2,test3,test5" Python中是否有一个函数,比如s.magic_replace_func(* replace_array
假设我有一个字符串s

s = "?,?,test4,test5"

我知道有三个问号,我想用下面的数组相应地替换每个问号

replace_array = ['test1','test2','test3']

获得

output = "test1,test2,test3,test5"

Python中是否有一个函数,比如s.magic_replace_func(* replace_array)可以实现预期的目标?

谢谢!

解决方法

使用str.replace并替换’?’使用'{}’,然后您可以使用str.format方法:

>>> s = "?,test5"
>>> replace_array = ['test1','test3']
>>> s.replace('?','{}',len(replace_array)).format(*replace_array)
'test1,test5'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读