How to convert a clojure keyword into a string?

Clojure

Clojure Problem Overview


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

Clojure Solutions


Solution 1 - Clojure

user=> (doc name)

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

Solution 2 - Clojure

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"

Solution 3 - Clojure

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"

Solution 4 - Clojure

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

Solution 5 - Clojure

This will also give you a string from a keyword:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSantoshView Question on Stackoverflow
Solution 1 - ClojurekotarakView Answer on Stackoverflow
Solution 2 - ClojuretxmikesterView Answer on Stackoverflow
Solution 3 - ClojureRafael MunitićView Answer on Stackoverflow
Solution 4 - ClojureSatyam RamawatView Answer on Stackoverflow
Solution 5 - Clojurematt whateverView Answer on Stackoverflow