5

I would like to use Replace function in a QGIS model but it doesn't work as I wish. I was working with Joseph's brilliant solution (using a custom script in a model) but I couldn't find out how to replace a specific character in a field. I would like to replace every '\' in Fromfield with '/' and write the result into Tofield. I tried this and a few more, but nothing:

##Test=name
##Layer=vector
##Tofield=Field Layer
##Fromfield=Field Layer

from qgis.core import QgsExpression

layer = processing.getObject(Layer)  
layer.startEditing()

idx = layer.fieldNameIndex(Tofield)
g= str(Fromfield)
e = QgsExpression(g.replace("\\","/"))
e.prepare(layer.pendingFields())

for f in layer.getFeatures():
    f[idx] = e.evaluate(f)
    layer.updateFeature(f)

layer.commitChanges()

Is this possible at all?

5

You should use the same syntax like in field calculator of QGIS (FC). From python there is a little hack you have to do. The working function in FC is:

replace("from_field", '\\' , '/')

From python, using QgsExpression, you will escape twice the backslash char, so the new function becomes:

'replace("' + Fromfield + '", \'\\\\\' ,\'/\')'

Your code should to work as follow:

from qgis.core import QgsExpression

layer = processing.getObject(Layer)  
layer.startEditing()

idx_to = layer.fieldNameIndex(Tofield)
e = QgsExpression(u'replace("' + Fromfield + '", \'\\\\\' ,\'/\')')
e.prepare(layer.pendingFields())

for f in layer.getFeatures():
    f[idx_to] = e.evaluate(f)
    layer.updateFeature(f)

layer.commitChanges()

Also, you can use only python here, without the QGIS API, with the following code:

layer = processing.getObject(Layer)  
layer.startEditing()

idx_to = layer.fieldNameIndex(Tofield)
idx_from = layer.fieldNameIndex(Fromfield)

for f in layer.getFeatures():
    f[idx_to] = f[idx_from].replace('\\' ,'/')
    layer.updateFeature(f)

layer.commitChanges()

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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