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

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:

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


Also published on Medium.