# Add Column and Populate using the Python Console

I am trying to add a new column to the attribute table and populate the column with a string, using the python console in QGIS. I have done the same but populating the column with an integer (FIELD_TYPE=1), which works fine, but as soon as I change the column to a string (FIELD_TYPE=2), it no longer works. The code I am trying to run:

out3 = "%s\\roth_vh_%s_3.shp"%(shpPath,year)
processing.runalg('qgis:fieldcalculator',\
out2,\
"polar",\
2,\
4,\
0,\
True,\
'vh',\
out3)


The error message I get is "Evaluation error: Column 'vh' not found". So for some reason it is looking for a column vh rather than taking it as the string to populate all the fields in the column with. It's confusing me though, because if I open the attribute table and run a field calculation to populate a column with a string, I would simply select the column, type the string into the field calculation bar (e.g. 'vh') and click update all, and it would work. Any ideas why the field calculation of 'vh' is not working in pyqgis please?

When you type vh as an expression in the Field Calculator, it assumes you are calling a field. If you type 'vh' (note the single quotes), it treats this as a string value.

In your code, you are doing the former (i.e. calling a field name). What you will need to do is call it as a string instead but be careful when using single quotes to specify a string parameter because you will also need single quotes to speficy the actual value. In which case, you would need to escape it using the following so that it reads 'vh' correctly:

'\'vh\''


So your code could look like:

out3 = "%s\\roth_vh_%s_3.shp"%(shpPath,year)
processing.runalg('qgis:fieldcalculator',\
out2,\
"polar",\
2,\
4,\
0,\
True,\
'\'vh\'',\
out3)


You could also use triple quotes to specify the string parameter and use an expression the same way you would write it in the Field Calculator:

""" 'vh' """,\