I have an attribute table in QGIS 2.10 with a string field (myfield) and when I want to make a selection based on the unique values of this field I get no selection at all.

>idxmyfield = mylayer.fieldNameIndex("myfield")
>uniquevalues = mylayer.uniqueValues(idxmyfield)
>[u'avalue', u'bvalue']
><type 'unicode'>

>y = len(uniquevalues)
>for x in range(y):
     it = mylayer.getFeatures(QgsFeatureRequest().setFilterExpression  (u' "myfield" = {0}'.format(uniquevalues[x])))
     mylayer.setSelectedFeatures([f.id() for f in it])
     selection = mylayer.selectedFeatures()

If I use another field with integer values the code is working. But if the values of the field are unicode/string it is not selecting anything.

So the type unicode differs from string or is it a type of string? If so, how can I change the type from unicode to string? Or how do I need to change the expression in order to get the selection I want?


You can convert a unicode string to a string this way:

s = u'UNICODE'
<type 'unicode'>
t = str(s)
<type 'str'>

But another issue is, that you missed the single quotes around your conditional argument when it is a string. When your condition is of type string you have to format the filter expression as following:

setFilterExpression(u' "myfield" = \'{0}\''.format(myfield[x]))

Remember: to enclose the single quote character in a single quoted string you must escape it.

>>> print ' "fieldname in double quotes" = \'condition in single quotes\' '
"fieldname in double quotes" = 'condition in single quotes'
|improve this answer|||||

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.