I did some tests (and some fails) on this code snippet:
layer=iface.activeLayer() # load the layer as you want
for feat in layer.getFeatures():
e = QgsExpression('concat((lpad("field1",2,0)),".",(lpad("field2",2,0)),".",(lpad("field3",3,0)),".",(lpad("field4",4,0)))')
value = e.evaluate()
before finding the solution, assuming that you are working on a layer with some fields ("field1"
, "field2"
, and so on).
Firstly, you can't call the fields in that way because they are not read correctly: writing "field1"
as is doesn't provide its value but rather a string that stores the "field1" text. In fact, using the code snippet above with your expression would print:
print value
[f[.][f[.][fi[.][fie
which doesn't make any sense. So, the first step was slightly changing the sample code:
layer=iface.activeLayer() # load the layer as you want
for feat in layer.getFeatures():
expr = 'concat((lpad(%s,2,0)),".",(lpad(%s,2,0)),".",(lpad(%s,3,0)),".",(lpad(%s,4,0)))' %(feat["field1"], feat["field2"], feat["field3"], feat["field4"])
e = QgsExpression(expr)
value = e.evaluate()
I thought it would be enough, but printing the value
variable gave me:
print value
01[.]06[.]015[.]0008
I solved the issue by using the char()
function instead of "."
(or '.'
). The char()
function, available from the Field Calculator, returns the character associated with a Unicode code. For the (full stop) dot, the Unicode code is 46 (see this Wikipedia page for reference). This was the final code:
layer=iface.activeLayer() # load the layer as you want
for feat in layer.getFeatures():
expr = 'concat((lpad(%s,2,0)),char(46),(lpad(%s,2,0)),char(46),(lpad(%s,3,0)),char(46),(lpad(%s,4,0)))' %(feat["field1"], feat["field2"], feat["field3"], feat["field4"])
e = QgsExpression(expr)
value = e.evaluate()
which printed the expected result:
print value
01.06.015.0008
Bonus If you want to store the result in a new field (e.g. "field5"
), adding these lines to the last code should be enough for updating it:
layer=iface.activeLayer() # load the layer as you want
for feat in layer.getFeatures():
expr = 'concat((lpad(%s,2,0)),char(46),(lpad(%s,2,0)),char(46),(lpad(%s,3,0)),char(46),(lpad(%s,4,0)))' %(feat["field1"], feat["field2"], feat["field3"], feat["field4"])
e = QgsExpression(expr)
value = e.evaluate()
with edit(layer):
feat["field5"] = value
layer.updateFeature(feat)