String Literals
Explore the different types of string literals in Elixir, including single-quoted and double-quoted strings, their encoding, escape sequences, and interpolation. Understand how heredocs preserve multiline strings and learn to use sigils to handle various literal forms such as strings, regular expressions, dates, and more. This lesson helps you gain practical knowledge of efficient string manipulation and pattern matching in Elixir.
Strings
Elixir has two kinds of strings: single-quoted and double-quoted. They differ significantly in their internal representation. But they also have many things in common. For example, see the following:
- Strings can hold characters in UTF-8 encoding.
- They may contain escape sequences:
`\a` BEL (0x07) `\e` ESC (0x1b) `\v` VT (0x0b) `\b` BS (0x08) `\f` FF (0x0c) `\s` SP (0x20) `\d` DEL (0x7f) `\n` NL (0x0a) `\t` TAB (0x09) `\r` CR (0x0d) `\xhh` 2 hex digits `\uhhh` 1–6 hex digits - They allow interpolation on Elixir expressions using the syntax
#{...}:iex> name = "dave" "Dave" iex> "Hello, #{String.capitalize name}!" "Hello, Dave!" - Characters that would otherwise have special meaning can be escaped with a backslash.
- They support heredocs.
Heredocs
Any string can span several lines. To illustrate this, we’ll use both IO.puts and IO.write. We use ...