How to convert list to string in Emacs Lisp
Asked Answered
G

5

40

How can I convert a list to string so I can call insert or message with it? I need to display c-offsets-alist but I got Wrong type argument: char-or-string-p for insert or Wrong type argument: stringp for message.

Georganngeorge answered 24/9, 2013 at 10:38 Comment(0)
A
64

I am not sure of what you are trying to achieve, but format converts "stuff" to strings. For instance:

(format "%s" your-list)

will return a representation of your list. message uses format internally, so

(message "%s" your-list)

will print it

Amphiaster answered 24/9, 2013 at 10:45 Comment(1)
Probably better %S instead of %s, to print the list in Lisp syntax.Rentsch
S
35

(format) will embed parentheses in the string, e.g.:

ELISP> (format "%s" '("foo" "bar"))
"(foo bar)"

Thus if you need an analogue to Ruby/JavaScript-like join(), there is (mapconcat):

ELISP> (mapconcat 'identity '("foo" "bar") " ")
"foo bar"
Selector answered 15/9, 2015 at 7:42 Comment(0)
I
10

Or

(prin1-to-string your-string)

Finally something special

(princ your-string)
Impermanent answered 24/9, 2013 at 11:17 Comment(0)
J
1
M-x pp-eval-expression RET c-offsets-alist RET
Jp answered 24/9, 2013 at 20:12 Comment(0)
P
0

If you need to convert a list like ((a b c d e)) to a string "a b c d e" then this function might help:

(defun convert-list-to-string (list)
  "Convert LIST to string."
  (let* ((string-with-parenthesis (format "%S" list))
     (end (- (length string-with-parenthesis) 2)))
    (substring string-with-parenthesis 2 end)))
Pitchman answered 2/5, 2021 at 14:58 Comment(5)
I don't want to get rid of parentheses I want to display a list or a tree as it is. If you have a list of strings and want to convert that to sting you have other options than substring. You can create a function to convert any type of string and use (string-join (map 'symbol-name '(foo bar baz)) " ") here I use symbol-name but it should be any->string.Georganngeorge
And your code will make no sense if you call it like this (convert-list-to-string '(foo bar (baz (quux)))) I think that you should ask another question because this is not the answer to my question.Georganngeorge
This is just my solution, taking the answer of Alexander Gromnitsky and getting rid of parenthesis. I stumbled upon the problem of converting a list like ((a b c d e)) to a string "a b c d e". This works for me and I hope will help someone else.Pitchman
This looks like an answer to a different question, how to convert ((a b c d e)) to a string "a b c d e"Georganngeorge
@Georganngeorge The question is "How to convert list to string in Emacs Lisp?" And I found your question trying to get an answer to mine. Alexander Gromnitsky answered my question and I adapted it. And if I found your question smb may also just need my answer for their same question "How to convert list to string in Emacs Lisp?"Pitchman

© 2022 - 2024 — McMap. All rights reserved.