Nick Ang profile picture

Nick Ang

How to add prefix or suffix to image urls in Python

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 to 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:

import re

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 ="(\.jpg|\.png)", image_url)
    if not index:
      return image_url
      # 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:]
    return image_url

add_suffix_to_image_url('', '_large')

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 ="(http://|https://)", image_url)

# Use index.end() to get index of end of matched term
index = index.end()

Additional notes: - See it in action on repl - Python regex documentation

Nick Ang profile picture
Senior software engineer, dad, writer-thinker type. Big on learning something everyday and trying to have fun before the lights go out.
contact  |  subscribe & access all latest posts