【问题标题】:Convert AppleScript List into String将 AppleScript 列表转换为字符串
【发布时间】:2016-05-18 02:27:26
【问题描述】:

我想知道是否有一种简单的方法可以将 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

【问题讨论】:

    标签: string list applescript


    【解决方案1】:

    有一个捷径,叫做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
    

    【讨论】:

    • 奇怪的是,在我在 macOS 10.13 上的测试中,我需要使用 AppleScript's text item delimiters 而不是仅仅使用 text item delimiters,否则它将不起作用。
    【解决方案2】:

    为此创建您自己的 sn-p

    将列表转换为字符串非常频繁,因此您最好创建一个子例程。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      相关资源
      最近更新 更多