Add a hyphen before the last 3 characters of variable length string

3205
7
Jump to solution
04-24-2015 05:32 AM
Highlighted
New Contributor II

Hi All. I'm looking for some VBScript help (or Python) to add a hyphen before the last 3 characters of variable length string. I can manage with fixed length strings, but not variable ones. 12345 = 12-345 and 123456 = 123-456.

Thanks in advance.

Luke

Tags (2)
Reply
0 Kudos
1 Solution

Accepted Solutions
Highlighted
MVP Esteemed Contributor

got to love slicing  (EDIT  oooops Sorry Vince ... was playing and didn't see you had posted already)

>>> a = '123456'

>>> out = a[:len(a)-3]+'-'+a[len(a)-3:]

>>> out

'123-456'

>>> a = '12345'

>>> out = a[:len(a)-3]+'-'+a[len(a)-3:]

>>> out

'12-345'

>>>

View solution in original post

7 Replies
Highlighted
Esri Esteemed Contributor

No matter the language, the task is the same:

  1. Compute string length
  2. Create new string composed of:
    1. substring(pos 1 to (len-3))
    2. hyphen
    3. substring(pos len-2 to len)

The syntax is different in each language, as well as the radix of the first character (0 or 1) and the exact invocation of the substring function.

- V

Highlighted
MVP Esteemed Contributor

got to love slicing  (EDIT  oooops Sorry Vince ... was playing and didn't see you had posted already)

>>> a = '123456'

>>> out = a[:len(a)-3]+'-'+a[len(a)-3:]

>>> out

'123-456'

>>> a = '12345'

>>> out = a[:len(a)-3]+'-'+a[len(a)-3:]

>>> out

'12-345'

>>>

View solution in original post

Highlighted
Esri Esteemed Contributor

No worries.  I often work with larger strings, which are O(N) in the length function, so I usually capture length once, vice embeding it twice. Yes, an optimizer might pick that up, but I like to pitch softly at optimizers.

- V

Reply
0 Kudos
Highlighted
New Contributor II

Thanks guys!

Reply
0 Kudos
Highlighted
MVP Regular Contributor

Don't forget to mark the post with the correct answer as correct

Reply
0 Kudos
Highlighted
Regular Contributor II

VBSCRIPT:

dim a as string

a = "MyFavoriteString123"

a = Left(a, Len(a) - 3) & "-" & Right(a, 3)

Highlighted
New Contributor II

Thanks Ted. I'm still learning...and always will be of course. I like this approach.

Reply
0 Kudos