The question of how to modify a URL in a recipe comes up often, particularly when using print_version. It's basic string handling in Python, but I thought I'd post some tips here:
The most common three ways this job (URL modification) is accomplished in recipes are to use : 1) replace, 2) partition/rpartition, and 3) split/join. You can read about them
here:
Use replace whenever you are replacing some part of the URL string (usually in the middle) with some other string and 1) the part being replaced never changes (this lets you find it) and 2) you don't want to change the two parts on either side of the part being replaced. You can keep the part you are replacing (by inserting itself back in) and you can add additional stuff in the middle, but you can't change the first and last parts.
Use partition/rpartition when you want to split the string into three parts and the part in the middle never changes (so you can find it), but you want to change one or more of the three parts.
If there isn't any unchanging part in the middle to find, then the solution most commonly used is split/join with splitting being done on the slash. It splits the URL into each part between slashes and you can do whatever you want to each piece, then put them together with join (which adds back the original slashes). You find the part to change by counting the cut up pieces (between slashes) and changing the pieces you need to change and inserting anything needed between them.
This shows a URL having the string "/v-print/" being inserted after the 6th slash to change
http://www.03.com/04/05/06/07/08.html
to
http://www.03.com/04/05/06/v-print/07/08.html:
Code:
def print_version(self,url):
segments = url.split('/')
printURL = '/'.join(segments[0:6]) + '/v-print/' + '/'.join(segments[6:])
return printURL
If you don't understand the [0:6] or [6:] usage, you need to read up on lists and string slices in Python
here.
Also see TonytheBookworm's
method described above.