I can't find an expression to add a character every nth character from the right of a string, in field calculator.

As an example, I have a list of UK postcodes which I need to add a space to 3 characters from the right:

From: N165KP To: N16 5KP

Note this has to be done from the right as the first lot of characters (before the space) can vary in length.

1 Answer 1


Try this:

left("Postcode", length("Postcode")-3) + ' ' + right("Postcode", 3)

It takes all characters of Postcode except the last three ones, adds a space and then appends the last three characters.

Edit.: I tested this in QGIS 2.18.22

  • Why not just to use left("Postcode", 3) || ' ' || right("Postcode", 3)?
    – Taras
    Nov 26, 2018 at 11:17
  • Your proposal turns DD115KP into DD1 5KP (Note the missing 1 in the middle). Nov 26, 2018 at 11:23
  • I thought the "Postcode" field is limited to six characters, but it is about n-characters. And I double checked the Note in the question, now it is clear.
    – Taras
    Nov 26, 2018 at 11:27

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.