将AppleScript列表转换为字符串

时间:2016-05-18 02:27:26

标签: string list applescript

我想知道是否有一种简短的方法可以将AppleScript列表转换为分隔每个项目的字符串。我可以用一种比我想要的更长的方式实现这一点,所以我想知道是否有一种简单的方法来实现这一点。基本上,我想采用{1,2,3}之类的列表并将其转换为字符串"1, 2, 3"。我可以执行类似下面的操作,但会在结果字符串后面生成逗号:

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

2 个答案:

答案 0 :(得分:4)

有一个简短的方法,它被称为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

答案 1 :(得分:0)

为此创建自己的代码段

将列表转换为字符串的频率很高,因此最好创建一个子例程。

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")