Tuesday, 15 April 2014

python - Insert a character into a url -



python - Insert a character into a url -

i getting set of urls in of them have same format. insert number within url.

for example:

in url = www.myblog.com.hghg$hfgh%hgh.113124534

i insert number declared number=444 come between somewhere, here after hghg, www.myblog.com.hghg444$hfgh%hgh.113124534

how can this?

if inser number @ given position (let 3).

you can, creating new strings originals:

number = 444 full_links = ["www.google.es", "wwww.stackoverflow.com"] in xrange(len(full_links)): full_links[i] = full_links[i][:3] + str(number) + full_links[i][3:]

and shorter:

full_links = [x[:3] + str(number) + x[3:] x in full_links]

you can't alter full_links in way iterating suggested (for links in full_links:) because:

python strings immutable. that loop construction implies link reference list string. assignation link won't alter list itself.

if had pattern or criteria found insert number value, alter comprehension list provided in order create insert position dynamic.

lets pattern "hghg":

full_links = ["www.google.es", "www.myblog.com.hghg$hfgh%hgh.113124534"] pattern = "hghg" full_links = [(x[:x.find(pattern)+len(pattern)] + str(number) + x[x.find(pattern)+len(pattern):]) if pattern in x else x x in full_links]

which can reduced (and optimized) to:

full_links = [ x.replace(pattern,pattern+str(number)) x in full_links]

python

No comments:

Post a Comment