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?

1 Answer 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, if i need to replace the fourth and fifth comma with ':' and the first three commas with '-', is there a way to specify range values also ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.