To add a suffix to an image url string in Python, you’ll need to use the
re (regular expression) module. We can use regex to identify the file format (eg .jpg or .png) and insert some text just before it.
Adding a suffix to image urls (eg. from
abc.com/img/image.jpg to abc.com/img/image_small.jpg) can be useful for getting smaller or larger images from a server that supports this handy technique. Shopify is a good example of a company that practices this.
Here’s the code:
def add_suffix_to_image_url(image_url, suffix):
Add suffix (eg. "_large") to image name just before .jpg or .png
# Find a match of '.jpg' or '.png'
index = re.search(r"(\.jpg|\.png)", image_url)
if not index:
# Get zero-based index of the start of the matched term in image_url
index = index.start()
# Doctor the string by splitting and rejoining with [:index] and [index:]!
return image_url[:index] + suffix + image_url[index:]
I’m not sure what use cases there might be for adding prefixes. Some cases probably exist but most likely not for image urls (?). In any case, to do that, just tweak the regex pattern:
# The same idea applies to adding prefix - just change the regex pattern
index = re.search(r"(http://|https://)", image_url)
# Use index.end() to get index of end of matched term
index = index.end()
Also published on Medium.