【问题标题】:Replace only few characters from list python仅替换列表 python 中的几个字符
【发布时间】:2013-06-22 17:31:35
【问题描述】:

我有一个格式如下的列表:

[ '2013,june,25,11,img1.ams.expertcity.com,/builds/g2m/1172/G2M_Mac_x86,84.83.189.112,3', '2013,june,25,11,img1.ams.expertcity.com,/builds/g2m/1172/G2MInstallerExtractor.exe,85.164.14.248,6', '2013,june,25,11,img1.syd.expertcity.com,/builds/g2m/1172/G2MCoreInstExtractor.exe,99.245.80.126,19']

我只需要将列表中每个元素的前三个逗号替换为“-”,即列表应如下所示:

[ '2013-june-25-11,img1.ams.expertcity.com,/builds/g2m/1172/G2M_Mac_x86,84.83.189.112,3', '2013-june-25-11,img1.ams.expertcity.com,/builds/g2m/1172/G2MInstallerExtractor.exe,85.164.14.248,6', '2013-june-25-11,img1.syd.expertcity.com,/builds/g2m/1172/G2MCoreInstExtractor.exe,99.245.80.126,19'] 

我尝试使用替换,但最终将所有“,”替换为“-”

mylist = [x.replace(",","-") for x in mylist]

我不想使用正则表达式,因为列表中的顺序可能会随着时间而改变。 请建议一个更好的方法来做到这一点?

【问题讨论】:

    标签: python regex list


    【解决方案1】:

    使用这个:x.replace(",","-",3)

    str.replace 有第三个可选参数count

    关于str.replace的帮助:

    S.replace(old, new[, count]) -> string
    

    返回字符串 S 的副本,其中包含所有出现的子字符串 old 换成新的。如果给出了可选参数 count,则只有 第一个 count 出现 被替换。

    【讨论】:

    • 您好,如果我需要将第四个和第五个逗号替换为“:”,前三个逗号替换为“-”,是否也可以指定范围值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2019-02-26
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    相关资源
    最近更新 更多