Convert String of Numbers to List of Numbers


(Jim Underwood) #1

I just discovered this very cool, compact script by @ShaneStanley, and just wanted to share it with you guys.

Thanks for a great script, Shane.


Topic Title:  How do I convert a string of numbers from text to a list if integers?
URL:    http://macscripter.netviewtopic.php?pid=169183#p169183

Date:    2013-11-28
Author:  Shane Stanley

Shane:  "It's a lot shorter, but takes a lot longer to run."

Note:  Script slightly modified by @JMichaelTX to add a bit of clarity.

--- It seems very fast to me in 2017-06-08, running Script Debugger 6.0.4 (6A198) on macOS 10.11.6 --

set stringOfNumbers to "1, -2, 3.1234, 4, -95.123"
set listOfNumbers to run script ("{" & stringOfNumbers & "}")

-->{1, -2, 3.1234, 4, -95.123}

(Shane Stanley) #2

I don’t know that I’d call any script that resorts to run script as cool – to me, it has a vaguely dirty feel about it. OTOH, in this particular case, it may be a good choice.

But I suspect that in the real world, most of the time the string will contain all reals or all integers, not a mixture of both. In those cases, using text item delimiters and coercing is really much nicer code IMO, as well as faster – and not particularly long.

Alternatively, and faster with longer lists:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set stringOfNumbers to "1, -2, 3.1234, 4, -95.123"
set stringOfNumbers to current application's NSString's stringWithString:stringOfNumbers
set listOfNumbers to ((stringOfNumbers's componentsSeparatedByString:",")'s valueForKey:"doubleValue") as list

(Jim Underwood) #3

But then, “cool” is like “beauty”. I’ll leave it at that.

Perhaps it is with longer lists, but not with short ones.
My test of the above running Script Debugger 6.0.4 (6A198) on macOS 10.11.6:

  • ASOBjC: 0.19 sec
  • Run Script: 0.01 sec

But it’s always good to have speciality tools when you need them.

(Shane Stanley) #4

Including for script timing. Script Debugger’s times are indicative, but the nature of a script editor means they can only ever be very rough. Try something like Script Geek:

It’s still not perfect – timing for AppleScript is always dependent on the host – but it eliminates a lot of overhead. Using it and the ASObjC method with a list of 40 entries, I time 100 iterations at 0.031 seconds. That’s about 0.0003 per iteration.

(Jim Underwood) #5

I tested both scripts using your Script Geek. I compiled each and then ran for 10 times:

I then ran both again (for 10 trials), and got identical results:

So, my conclusion has not changed. At least for small lists, there is no penalty for using the original script that used run script, and there may be a small performance advantage. The run script method also offers a very compact solution, and works with both integers and reals in the same list.