Thursday, 13 September 2018

pyqgis - Syntax error in parameter formula of field calculator funtion


I'm using a QGIS 2.8.1 in windows. Have some doubts with syntax when use string in python console. I want to use the field calculator funtion like:


processing.runalg('qgis:fieldcalculator', input, field_name, type_field, width, precision, Create new field, formula, output)


In the formula parameter I want use the condition:


case when "Municipio" is NULL then 'PENICHE'

I know that PENICHE is a string, so have to be between '' (plicas) but all the expression should be too between '' (plicas) like:


' case when "Municipio" is NULL then 'PENICHE' ' 

The problem is that there happened a syntax error.


How can I correct the expression?





The code I´m using is:


processing.runalg('qgis:fieldcalculator', input, "Mun", 2, 27, 0, True, ' case when "Municipio" is NULL then 'PENICHE' else "Municipio" end ', output)




I used formula = "case when \"Municipio\" is NULL then 'PENICHE' end" know its working!



Answer



While Joseph is correct about the syntax of the CASE statement, your Python issue stems from string quoting.


You can use either ' or " to quote strings, and you don't have to escape the other character if used, but you do have to escape the same character. Or you can triple quote (ie ''') which will also allow multi line quotes.


In other words:


# this should work 
formula = "case when \"Municipio\" is NULL then 'PENICHE' end"

# so should this
formula = 'case when "Municipio" is NULL then \'PENICHE\' end'

# or you can use multi line quotes
formula = '''
case when "Municipio" is NULL then 'PENICHE' end
'''

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...