I am using QGIS with the in-built Python console. I want to replace some values in a shapefile with some other values. But when I try to change the attribute values, I get an error about the data types (see the code below):
Error: AttributeError: 'QVariant' object has no attribute 'split'
However, I find no way to convert the QVariant to a String. If I run the code without the editing turned on, everything works fine, but the changes are not saved. How can I convert the QVariant to a string and are there ways around this issue?
shp_layer = QgsVectorLayer(shp_path, "", "ogr")
with edit(shp_layer):
for feature in shp_layer.getFeatures():
height_str_list = feature[height_list_field].split(":", 1)[1][:-1].split(",") # some fancy string editing in here, but i swear it works
if '...' in height_str_list:
height_str_list.remove('...')
height_flt_list = [float(i) for i in height_str_list]
feature[height_field] = sum(height_flt_list)/len(height_flt_list) # because QGIS pretends not to know mean()
shp_layer.updateFeature(feature)
shp_layer.setSubsetString("")
I also discovered if I say height_str_list = feature[height_list_field].value().split(....)
I get another error:
"AttributeError: 'str' object has no attribute 'value'"