如何将 clojure 关键字转换为字符串?

在我的应用程序中,我需要将 clojure 关键字,例如: var _ name 转换为字符串“ var _ name”。有什么办法吗?

36978 次浏览
user=> (doc name)
-------------------------
clojure.core/name
([x])
Returns the name String of a string, symbol or keyword.
nil
user=> (name :var_name)
"var_name"

Note that kotarak's answer won't return the namespace part of keyword, just the name part - so :

(name :foo/bar)
>"bar"

Using his other comment gives what you asked for :

(subs (str :foo/bar) 1)
>"foo/bar"

Actually, it's just as easy to get the namespace portion of a keyword:

(name :foo/bar)  => "bar"
(namespace :foo/bar) => "foo"

Note that namespaces with multiple segments are separated with a '.', not a '/'

(namespace :foo/bar/baz) => throws exception: Invalid token: :foo/bar/baz
(namespace :foo.bar/baz) => "foo.bar"

And this also works with namespace qualified keywords:

;; assuming in the namespace foo.bar
(namespace ::baz) => "foo.bar"
(name ::baz) => "baz"

This will also give you a string from a keyword:

(str (name :baz)) -> "baz"
(str (name ::baz)) -> "baz"

It's not a tedious task to convert any data type into a string, Here is an example by using str.

(defn ConvertVectorToString []
(let [vector [1 2 3 4]]
(def toString (str vector)))
(println toString)
(println (type toString)
(let [KeyWordExample (keyword 10)]
(def ConvertKeywordToString (str KeyWordExample)))
(println ConvertKeywordToString)
(println (type ConvertKeywordToString))


(ConvertVectorToString) ;;Calling ConvertVectorToString Function


Output will be:
1234
java.lang.string
10
java.lang.string