1

I have a list which is of the following format:

[ '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']

I need to replace only the first three commas with '-' for each element of the list i.e the list should look like this:

[ '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'] 

I tried to use replace but it ends up replacing all ',' with '-'

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

I do not want to use regex because the order in the list might change over time. Please suggest a better way to do this?

4

1 回答 1

5

Use this : x.replace(",","-",3)

str.replace has a third optional argument count.

help on str.replace:

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

Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

于 2013-06-25T19:05:22.050 回答