5

I am working with a Mac OSX El Capitan, QGIS 3.4.5 Madeira and Python 3.6.1.

I have a question which I believe is essentially a python one but applied into QGIS.

I intend to program some algorithms from the Saga tools to run various files. So, for instance I want to clip a raster with a polygon and so I run the following:

processing.run("saga:cliprasterwithpolygon", { 'INPUT' : '/Users/.../wheat_HarvestedAreaHectares.tif', 
'OUTPUT' : '/Users/.../wheat.sdat', 
'POLYGONS' : '/Users/.../africa_countries.shp' })

The raster files are agricultural data from all the world and I am clipping it to a shape file of the African continent to do some computations afterwards with zonal statistics.

Naturally, I would love to find a way to run this code for several crops. I am imagining something as creating a list with the names of the crops and looping through the code with the name of the crop as a macro.

Something like:

crop = [maize, wheat, rice]
for crop in crops:
    processing.run("saga:cliprasterwithpolygon", { 'INPUT' : '/Users/.../`crop'_HarvestedAreaHectares.tif', 
        'OUTPUT' : '/Users/.../`crop'.sdat', 
        'POLYGONS' : '/Users/.../africa_countries.shp' })

However, I've read elsewhere that Python does not work with macros, and similar questions around stackexchange does not seem to address this issue directly.

Any hint?

1 Answer 1

4

what you're describing is called ‘string interpolation’.

In days of old, you could simply add strings together with the + operator, but this looks a bit ugly.

As you're using Python 3.6, the easiest way is called “f-strings”, which is new to Python 3.6

I admit I’ve not tried this, but something like this should do the trick. Put an 'f' before the string, and put the variable name in {curly_brackets}

crop = ['maize', 'wheat', 'rice']
for crop in crops:
    processing.run("saga:cliprasterwithpolygon", { 'INPUT' : f'/Users/.../{crop}_HarvestedAreaHectares.tif', 
        'OUTPUT' : f'/Users/.../{crop}.sdat', 
        'POLYGONS' : '/Users/.../africa_countries.shp' })
2
  • 1
    That was great Steven! I am just adding for future references that the list should be written in the following way crop = ['maize', 'wheat', 'rice'] as they are strings. Also, f as you has written wouldn't work with the apostrophe symbol you put (f’) but should instead use the symbol of seconds (f') (they are actually different). So be careful if you are copying Steven's code! Commented Jun 5, 2019 at 16:59
  • 1
    thanks for the feedback! I've fixed the code, should be good now. I use Javascript more these days, where backticks are used for the same functionality, so I didn't pick it up :-)
    – Steven Kay
    Commented Jun 5, 2019 at 18:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.