17

Is it possible to make a new column, for example named "Test" and store the first part of the column "Name" split by -?

See below how it should look like:

example

1
  • 2
    Couldn't you use python's .split() function?
    – Branco
    Commented Dec 22, 2014 at 20:53

3 Answers 3

25

Yes you can.

Use the Field calculator with the following expression:

left( "Name", strpos( "Name" ,'-'))

The strpos() function will return the index position of the first '-' character and the left() function "trims" the string before that position.

enter image description here

4
  • That works, but "Name".split('-')[0], per @Branco, might be easier.
    – recurvata
    Commented Dec 23, 2014 at 14:01
  • Can you use it in field calculator? Otherwise you need to use the python console to iterate over the features. Compared to that, the field calculator looks more straightforward. There might be better expression using regular expressions. Commented Dec 23, 2014 at 14:41
  • 5
    You can not use it in filed calculator. So answer provided by Alexandre Neto is more straight forward. But is better to use it with "-1" to avoid adding your charater to output. For example: left( "Name", strpos( "Name" ,':')-1). Otherwise you will end up with "3833-" not just "3833"
    – Losbaltica
    Commented Jun 12, 2017 at 13:49
  • can any one help me to split entire column at a time by '-'. like text to column in excel
    – Bruno B
    Commented Oct 28, 2021 at 6:55
15

You can use the Field calculator with the following expression:

string_to_array("Nombre", ' ')

enter image description here

The string_to_array() function splits string into an array using supplied delimiter.

If you want a some position of the array, you can add the position and it will return the value. like this:

string_to_array("Nombre", ' ')[2]

enter image description here

3

Possible solution by means of PyQGIS.

Let's assume there is a point layer called "some_points" with it's attribute table, see image below.

input

Proceed with Plugins > Python Console > Show Editor and paste the script below

from PyQt5.QtCore import QVariant

layer = iface.activeLayer()
if not layer.isValid():
    print("Layer failed to load!")

layer_provider = layer.dataProvider()
layer_provider.addAttributes([QgsField("Test", QVariant.String)])
layer.updateFields()

features=layer.getFeatures()

layer.startEditing()

for f in features:
    attrs = {2: f['info'].split('-')[0]}
    layer_provider.changeAttributeValues({f.id(): attrs})
layer.commitChanges()

python_console

The output will be looking

result


References:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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