Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 36 ยท Language Basics

Strings, Characters, Keywords and Symbols

Work with text in Clojure: string functions in clojure.string, characters, regular expressions, format, and how keywords and symbols differ and are used as names and map keys.

Text in Clojure comes in four related forms. Strings hold text, characters are single letters, keywords are self-describing names that are mostly used as map keys, and symbols are names that the evaluator resolves to values. This lesson covers all four plus regular expressions.

Strings

A string is written in double quotes and is an ordinary Java String. Strings can span lines, and the usual escapes work (\n, \t, \", \\, รฉ).

CLOJURE
"Hello"
"line one\nline two"
"She said \"hi\""

Strings are immutable. Every operation returns a new string.

Core string functions

CLOJURE
(str "a" "b" 1 :c)        ; "ab1:c"
(count "hello")           ; 5
(subs "hello world" 6)    ; "world"
(subs "hello world" 0 5)  ; "hello"
(get "abc" 1)             ; \b
(first "abc")             ; \a
(reverse "abc")           ; (\c \b \a)   a sequence of chars!
(apply str (reverse "abc"))  ; "cba"

Many sequence functions (first, rest, map, filter, reverse) treat a string as a sequence of characters, so they return sequences. Use apply str or clojure.string/join to turn the result back into a string.

The clojure.string namespace

Text utilities live in clojure.string, usually required with the alias str:

CLOJURE
(require '[clojure.string :as str])

(str/upper-case "clojure")           ; "CLOJURE"
(str/lower-case "CLOJURE")           ; "clojure"
(str/capitalize "hELLO")             ; "Hello"
(str/trim "  padded \n")             ; "padded"
(str/blank? "   ")                   ; true
(str/includes? "functional" "ion")   ; true
(str/starts-with? "clojure" "clo")   ; true
(str/ends-with? "clojure" "ure")     ; true
(str/index-of "banana" "na")         ; 2
(str/split "a,b,c" #",")             ; ["a" "b" "c"]
(str/join ", " ["a" "b" "c"])        ; "a, b, c"
(str/replace "a-b-c" "-" "_")        ; "a_b_c"
(str/replace "a1b22" #"\d+" "#")     ; "a#b#"
(str/split-lines "one\ntwo")         ; ["one" "two"]

Note the argument order: for str/join the separator comes first, and for str/split the string comes first. Reading (doc str/join) in the REPL clears up any doubt.

JS Stand-in: common string operations

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Characters

A character literal starts with a backslash: \a, \Z, \7, and the named characters \space, \newline, \tab, \return. Unicode characters use รฉ.

CLOJURE
(char 65)          ; \A
(int \A)           ; 65
(str \a \b)        ; "ab"
(Character/isDigit \5)   ; true
(Character/isLetter \x)  ; true

A character is not a one-character string: (= \a "a") is false. Remember the difference when you compare values taken from a string with get, first or seq.

Regular expressions

A regular expression literal is #"pattern". Remember that backslashes in the pattern are written once, because the reader handles #"..." specially:

CLOJURE
(re-find #"\d+" "order 42 shipped")      ; "42"
(re-matches #"\d+" "42")                 ; "42"      (must match the whole string)
(re-matches #"\d+" "42x")                ; nil
(re-seq #"\d+" "1 and 22 and 333")       ; ("1" "22" "333")
(re-find #"(\w+)@(\w+)\.com" "[email protected]")
;; => ["[email protected]" "ann" "site"]     (groups come back in a vector)

re-find finds the first match, re-matches requires the entire string to match, and re-seq returns all matches lazily. With groups, the result is a vector: the whole match followed by each group.

Formatting and building strings

CLOJURE
(format "%s is %d years old" "Ada" 36)   ; "Ada is 36 years old"
(format "%.2f" 3.14159)                  ; "3.14"
(format "%5d|%-5d|" 42 42)               ; "   42|42   |"
(str "Total: " 12 " items")              ; "Total: 12 items"

For longer text, str and format combine well. If you build a string in a loop, use str/join or with-out-str rather than repeated concatenation. Clojure 1.12 does not ship string interpolation, so (str "Hello, " name "!") is the standard approach.

Keywords

A keyword starts with a colon: :name, :user/id, :admin?. It always evaluates to itself, and two keywords with the same name are the same object, so they compare very quickly. That makes them ideal as map keys and as tags for options.

CLOJURE
(def person {:name "Ada" :age 36})
(:name person)        ; "Ada"   a keyword can be called as a function
(:email person)       ; nil
(:email person "n/a") ; "n/a"   with a default
(keyword "city")      ; :city
(name :city)          ; "city"
(namespace :user/id)  ; "user"

Keywords that carry a namespace, like :user/id or :order/total, avoid clashes between different domains. The double-colon ::id expands to the current namespace, so inside shop.core it means :shop.core/id. A keyword used as a function that looks itself up in a map is a very common idiom and is the reason keywords are preferred over strings for keys.

Symbols

A symbol is a name that the evaluator resolves. Writing inc produces the symbol inc, which evaluates to the function it names. Quote it to get the symbol itself:

CLOJURE
'inc                 ; the symbol inc
(symbol "foo")       ; foo
(name 'user/foo)     ; "foo"
(= 'a 'a)            ; true
(symbol? 'a)         ; true

Symbols matter chiefly when you write macros, work with namespaces ((require 'clojure.string) quotes the namespace symbol) and inspect code. In everyday code you mostly use them without thinking, as the names of functions and local variables.

Four kinds of text-like values

String "hello" holds text
Character \a is one letter
Keyword :name refers to itself
Symbol inc is looked up

Keywords are the usual map keys.

1 / 2

Using keywords as functions, modelled in JavaScript

JavaScript has no keywords, but a small stand-in shows how (:key map) behaves and why defaults are convenient.

JS Stand-in: keyword lookup with default

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In Clojure, the last line is simply (map :name people).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (apply str (reverse "abc")) return?

    reverse returns a sequence of characters; apply str joins them back into the string "cba".
  2. 2. What is the difference between \a and "a"?

    A character and a one-letter string are different types and are not equal.
  3. 3. Which call returns every number in a string as a sequence of matches?

    re-seq returns all matches; re-find returns only the first and re-matches needs a full match.
  4. 4. What does (:email {:name "Ada"} "n/a") return?

    A keyword used as a function looks itself up in the map; the second argument is the default.

Summary

  • Strings are immutable Java strings; clojure.string (alias str) holds the text utilities.
  • Many sequence functions return character sequences; turn them back with (apply str ...) or str/join.
  • Characters are written \a and are not strings.
  • #"..." creates a regex; use re-find, re-matches and re-seq.
  • Keywords evaluate to themselves, work as functions on maps and are the usual map keys; symbols are names resolved by the evaluator.

Next: Booleans, nil and Conditionals