Reputation: 1958
In my application I need to convert clojure keyword eg. :var_name into a string "var_name". Any ideas how that could be done?
Upvotes: 116
Views: 42231
Reputation: 37
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
Upvotes: -2
Reputation: 1
This will also give you a string from a keyword:
(str (name :baz)) -> "baz"
(str (name ::baz)) -> "baz"
Upvotes: -3
Reputation: 191
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"
Upvotes: 18
Reputation: 927
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"
Upvotes: 16
Reputation: 17299
user=> (doc name)
-------------------------
clojure.core/name
([x])
Returns the name String of a string, symbol or keyword.
nil
user=> (name :var_name)
"var_name"
Upvotes: 187