How to convert a clojure keyword into a string?
在我的应用程序中,我需要转换clojure关键字,例如。 :var_name转换为字符串" var_name"。 有什么想法可以做到吗?
1 2 3 4 5 6 7 8 | user=> (doc name) ------------------------- clojure.core/name ([x]) Returns the name String of a string, symbol or keyword. nil user=> (name :var_name) "var_name" |
实际上,获取关键字的名称空间部分同样容易:
1 2 | (name :foo/bar) =>"bar" (namespace :foo/bar) =>"foo" |
请注意,具有多个段的名称空间以"。"而不是" /"分隔。
1 2 | (namespace :foo/bar/baz) => throws exception: Invalid token: :foo/bar/baz (namespace :foo.bar/baz) =>"foo.bar" |
这也适用于名称空间限定关键字:
1 2 3 | ;; assuming in the namespace foo.bar (namespace ::baz) =>"foo.bar" (name ::baz) =>"baz" |
请注意,kotarak的答案不会返回关键字的名称空间部分,而仅返回名称部分-因此:
1 2 | (name :foo/bar) >"bar" |
使用他的其他评论给出您想要的:
1 2 | (subs (str :foo/bar) 1) >"foo/bar" |
将任何数据类型转换为字符串不是一件繁琐的任务,这是使用str的示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | (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 |
这也会给您一个来自关键字的字符串:
1 2 | (str (name :baz)) ->"baz" (str (name ::baz)) ->"baz" |