简体   繁体   中英

Replace only few characters from list python

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 ie 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM