Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert AppleScript List into String

I was wondering if there is a short way to convert an AppleScript list into a string separating each item. I can achieve this in a way which is more lengthy that I would like, so I wondered if there is a simple way to achieve this. Basically, I would like to take a list such as {1,2,3} and convert it in to a string "1, 2, 3". I can do something like below, but that results in a comma following the resulting string:

set myList to {"1.0", "1.1", "1.2"}
set Final to ""
if (get count of myList) > 1 then
    repeat with theItem in myList
        set Final to Final & theItem & ", "
    end repeat
end if
like image 270
Cornelius Qualley Avatar asked May 18 '16 02:05

Cornelius Qualley


2 Answers

There is a short way, it's called text item delimiters

set myList to {"1.0", "1.1", "1.2"}
set saveTID to text item delimiters
set text item delimiters to ", "
set Final to myList as text
set text item delimiters to saveTID
like image 200
vadian Avatar answered Nov 15 '22 08:11

vadian


Create your own snippet for this

Convert a list to a string is so frequent that you better create a subroutine.

on list2string(theList, theDelimiter)

    -- First, we store in a variable the current delimiter to restore it later
    set theBackup to AppleScript's text item delimiters

    -- Set the new delimiter
    set AppleScript's text item delimiters to theDelimiter

    -- Perform the conversion
    set theString to theList as string

    -- Restore the original delimiter
    set AppleScript's text item delimiters to theBackup

    return theString

end list2string

-- Example of use
set theList to {"red", "green", "blue"}
display dialog list2string(theList, ", ")
display dialog list2string(theList, "\n")
like image 30
ePi272314 Avatar answered Nov 15 '22 08:11

ePi272314