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
Solved! Go to Solution.
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' >>>
No matter the language, the task is the same:
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
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' >>>
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
Thanks guys!
Don't forget to mark the post with the correct answer as correct
VBSCRIPT:
dim a as string a = "MyFavoriteString123" a = Left(a, Len(a) - 3) & "-" & Right(a, 3)
Thanks Ted. I'm still learning...and always will be of course. I like this approach.