114

In my application I need to convert clojure keyword eg. :var_name into a string "var_name". Any ideas how that could be done?

Santosh
  • 1,928
  • 2
  • 15
  • 13

5 Answers5

184
user=> (doc name)
-------------------------
clojure.core/name
([x])
  Returns the name String of a string, symbol or keyword.
nil
user=> (name :var_name)
"var_name"
kotarak
  • 17,099
  • 2
  • 49
  • 39
16

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"
txmikester
  • 171
  • 1
  • 2
15

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"
Rafael Munitić
  • 897
  • 2
  • 9
  • 21
-1

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
-2

This will also give you a string from a keyword:

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