In my application I need to convert clojure keyword eg. :var_name into a string "var_name". Any ideas how that could be done?
Asked
Active
Viewed 3.9k times
5 Answers
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
-
3I cannot imagine a more complete answer, but just for fun I shall dare someone to come up with it. – Hamish Grubijan Sep 15 '10 at 15:55
-
3@Hamish Perhaps by adding `(source name)`? – ponzao Sep 15 '10 at 18:05
-
2How `name` works should not be of interest. The docstring is the contract. Anything else is an implementation detail, one should not rely upon. – kotarak Sep 15 '10 at 19:32
-
1Thanks! My initial reaction was to do this: (.replaceFirst (.toString (keyword "abc")) ":" "") – Susheel Javadi Sep 16 '10 at 06:26
-
3Thanks kotarak! I am loving this Clojure more every day! This is my third day. – Santosh Sep 16 '10 at 08:46
-
@BartJ: `(doc subs)` => `(subs (str (keyword "abc")) 1)` ;) – kotarak Sep 16 '10 at 10:01
-
5Maybe this answer should explain why `(name :foo/123/bar)` is "bar". If you want the full path of a keyword you need to use `subs` or something like `(str (namespace k) "/" (name k))` – AnnanFay Apr 06 '12 at 13:48
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

Satyam Ramawat
- 39
- 4
-2
This will also give you a string from a keyword:
(str (name :baz)) -> "baz"
(str (name ::baz)) -> "baz"

matt whatever
- 1
- 1