Select to view content in your preferred language

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

5702
7
Jump to solution
04-24-2015 05:32 AM
LukeSnyder
Occasional Contributor

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)
0 Kudos
1 Solution

Accepted Solutions
DanPatterson_Retired
MVP Emeritus

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
VinceAngelo
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

DanPatterson_Retired
MVP Emeritus

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'
>>>
VinceAngelo
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

0 Kudos
LukeSnyder
Occasional Contributor

Thanks guys!

0 Kudos
TimWitt2
MVP Alum

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

0 Kudos
TedKowal
Honored Contributor

VBSCRIPT:

dim a as string 
a = "MyFavoriteString123" 
a = Left(a, Len(a) - 3) & "-" & Right(a, 3)
LukeSnyder
Occasional Contributor

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

0 Kudos