2

so I have a data as follows:

 item = '//s780.scene7.com/is/image/forever/301596014_001?hei=98&wid=98'

using urlparse module. how can i replace the above data with a new size to make it look like this:

  item = '//s780.scene7.com/is/image/forever/301596014_001?hei=360&wid=360'
James A Mohler
  • 11,060
  • 15
  • 46
  • 72
slopeofhope
  • 686
  • 2
  • 6
  • 21

4 Answers4

7

Here is an answer which, as requested, uses urlparse:

import urllib
import urlparse

url = '//s780.scene7.com/is/image/forever/301596014_001?hei=98&wid=98'
parts = urlparse.urlparse(url)
query_dict = urlparse.parse_qs(parts.query)  # {'wid': ['98'], 'hei': ['98']}
query_dict['wid'] = '360'
query_dict['hei'] = '360'
new_parts = list(parts)
new_parts[4] = urllib.urlencode(query_dict)
print urlparse.urlunparse(new_parts)
audiodude
  • 1,865
  • 16
  • 22
  • hm....i get this value //s780.scene7.com/is/image/forever/301596014_001;wid=360&hei=240?hei=98&wid=98 how do i get rid of this part here hei=98&wid=98 – slopeofhope Oct 06 '14 at 18:20
1

I like doing it this way to keep it easy to read:

from urllib.parse import urlsplit, urlunsplit, urlencode

split = urlsplit(url)
new_url = urlunsplit((
    split.scheme,
    split.netloc,
    split.path,
    urlencode(dict(hei=360, wid=360)),
    None,
))
rbutus
  • 11
  • 2
0

Is that what you want ?

item_360 = item.replace("=98","=360")
print item_360
'//s780.scene7.com/is/image/forever/301596014_001?hei=360&wid=360'

I put "=" to avoid replacing number before (if exist).

For more complex replacement you can have a look to regex

So, if you don't know 98, you can use regex :

import re
item_360 = re.sub("=\d+", '=360', item)
jrjc
  • 21,103
  • 9
  • 64
  • 78
0

if hei and wid always equal one number ,so we have :

 a = item[item.find('=')+1:item.find('&')] #this is the number in url (in your example it is 98
 item.replace(a, '360')   #item.replace(a, NewNumber) 

hope it helps :)

Alireza Sanaee
  • 465
  • 1
  • 7
  • 21