I have some fields calculations and I want to create a pyqgis plugin using my expressions but I get Unexpected errors. For example if I do my task using field calculator in QGIS then it works, if i use the same expression in QGIS modeler it works again but does not work when using the same expression in pyqgis.
I dont know why because I use the same expression.

Here is the pyqgis code :

outputs_QGISFIELDCALCULATOR_6=processing.runalg('qgis:fieldcalculator', outputs_QGISFIELDCALCULATOR_5['OUTPUT_LAYER'],'mynewfield',1,10.0,0.0,True,'left( "field1", strpos( "field1" ,'_')-1)',None)

and I get syntax error.

that is from model export and in the model working nice.

Finally i try advanced python field calculator but that now work for me.

If I use value=left( "field1", strpos( "field1" ,'_')-1) then I get error no module left. If i use value='left( "field1", strpos( "field1" ,'_')-1)' then I get this error - error

  • 1
    It's very likely that it's having an issue with how you are quoting strings within the expression. Check out the answer to this question: gis.stackexchange.com/questions/160698/…. So, I would expect something like value='left( "field1", strpos( "field1" ,\'_\')-1)' to perhaps work.
    – JohnR
    Apr 26, 2017 at 19:52

1 Answer 1


In your PyQGIS code when you are writing the expression -

'left( "field1", strpos( "field1" ,'_')-1)'

use escape characters for defining quotes inside like -

'left( \"field1\", strpos( \"field1\" ,\'_\')-1)'

I've tried it on QGIS 2.18 and it should work for you.

As as far as the Advanced Python Field Calculator goes, it works quite different from the default QGIS Field Calculator. You may refer this blogpost for more information about its use.

  • Is it necessary to escape the " characters, or would it suffice to only escape the ' characters since they're the ones used to contain the expression?
    – JohnR
    Apr 26, 2017 at 19:58
  • It would suffice to just escape ' in this case. However if the expression would have been enclosed in " then the opposite would be true. In my experience it is better to escape all the quotes as the expression may be written in any manner.
    – nash
    Apr 26, 2017 at 20:03
  • Another effective way would be to use triple quote ''' which would remove any necessity for escape characters. Thank you @JohnR for the link in your comment where I found this information.
    – nash
    Apr 26, 2017 at 20:14
  • @nash thank you i follow proposal by nash and problem sovled thank you again good job
    – hellas
    Apr 27, 2017 at 13:36

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.