I have a number of shapefiles with a field in the attribute table containing many different string values similar to this one: 'Waypoints_17-JUL-18Timothy waypoints.shp Waypoints_17-JUL-18Timothy waypoints.' The only difference in the values is the name. I would like to find a way in PyQGIS to remove everything after the first name, so before 'waypoints.shp...' and iterate through each of the fields to repeat this. Is it possible to do this in PyQGIS? I am new to PyQGIS so am unsure where to start but it should be a lot quicker than doing manually. I am using QGIS 3.0.0

  • Which QGIS version are you using? If you have a value "Waypoints_17-JUL-18Timothy waypoints.shp Waypoints_17-JUL-18Timothy waypoints", you just want to instead have "Waypoints_17-JUL-18Timothy"?
    – Joseph
    Aug 15 '18 at 12:47
  • @Joseph I am using QGIS 3.0.0. Yes, that is correct. However, some fileds have different names, e.g. 'John' instead of 'Timothy,' so I need to remove everything after this name / before the next section, which always starts with 'waypoints.shp...' as in the above example
    – Simba06
    Aug 15 '18 at 12:50

Assuming you only want to keep the first part of the value (i.e. before the first space), you could try using the following:

layer = iface.activeLayer()
with edit(layer):
    for feature in layer.getFeatures():
        new_value = feature['fieldName'].split(' ', 1)[0]
        feature.setAttribute(feature.fieldNameIndex('fieldName'), new_value)
  • 1
    Is activeLayer the top most layer in layer tree?
    – BERA
    Aug 15 '18 at 13:31
  • 1
    @BERA - No, it's the layer currently selected in the tree. So you would want to make sure you select the correct layer :)
    – Joseph
    Aug 15 '18 at 13:32
  • @JClifford - Most welcome! Glad it helped :)
    – Joseph
    Aug 15 '18 at 14:38

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.