36

Is there a function in Emacs Lisp that does the opposite of split-string, i.e. joins the elements of a list into string delimited by a given delimiter? In other words, is there a function that given a list, e.g. ("foo" "bar" "baz"), and a delimiter, e.g. ", ", returns that list as a string delimited by that delimiter, e.g. "foo, bar, baz".

Common Lisp seems to have such a function but the function with the same name in Emacs Lisp, format, is a wholly different function.

Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38
N.N.
  • 8,336
  • 12
  • 54
  • 94

4 Answers4

51

I think you are looking for mapconcat:

mapconcat applies function to each element of sequence: the results, which must be strings, are concatenated. Between each pair of result strings, mapconcat inserts the string separator. Usually separator contains a space or comma or other suitable punctuation.

Volker Stolz
  • 7,274
  • 1
  • 32
  • 50
  • 53
    [`(mapconcat 'identity '("foo" "bar" "baz") ", ")`](http://www.rhinocerus.net/forum/lang-lisp/576185-emacs-lisps-mapconcat-common-lisp.html#post2300674) – N.N. Oct 21 '12 at 16:43
  • 5
    The example made this answer much more useful. – Benilda Key Nov 05 '15 at 19:45
  • 3
    default package of emacs 24.5 `24.5/lisp/emacs-lisp/subr-x.el` has the same function as mentioned by @N.N. named `string-join`. – displayname Aug 27 '16 at 12:08
45

Emacs has string-join since 24.4 as part of subr-x.el:

(eval-when-compile (require 'subr-x))
(string-join '("one" "two" "three") ", ") ; ==> "one, two, three"

subr-x.el contains also other useful (string manipulation) functions - from the 24.4 release notes:

New library subr-x.el for misc helper functions

hash-table-keys
hash-table-values
string-blank-p
string-empty-p
string-join
string-reverse
string-trim-left
string-trim-right
string-trim
string-remove-prefix
string-remove-suffix
user272735
  • 10,473
  • 9
  • 65
  • 96
Joost Kremers
  • 551
  • 4
  • 4
  • 3
    That's nice! From where did you get this reference? I couldn't find on the docs. https://www.gnu.org/software/emacs/manual/html_mono/elisp.html – bcfurtado Jun 14 '18 at 01:14
  • `string-join` is part of [subr-x.el](https://emacsredux.com/blog/2014/02/02/a-peek-at-emacs-24-dot-4-new-string-manipulation-functions/). – user272735 Jan 27 '21 at 07:46
12

If you use string manipulation heavily in your Elisp, i recommend you to install a library s.el, which has a vast and consistent API for strings. For your task it has a function s-join:

(s-join "+" '("abc" "def" "ghi")) ;; => "abc+def+ghi"
(s-join "\n" '("abc" "def" "ghi")) ;; => "abc\ndef\nghi"
Mirzhan Irkegulov
  • 17,660
  • 12
  • 105
  • 166
8

Depending what you're doing, there may be a better function eg if you're building command line args, use combine-and-quote-strings which does the work for you.

(combine-and-quote-strings '("foo" "bar" "baz") ", ")
"foo, bar, baz"
robert
  • 4,612
  • 2
  • 29
  • 39
zombieRMS
  • 81
  • 1
  • 1