Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Language Basics

Printing Output and Working with Strings

Print with io:format and its control sequences, understand why Erlang strings are lists of integers, and use the string module, binaries and iolists.

Erlang has no dedicated string type. A string in double quotes is a list of integers, one per character. That choice makes some things delightfully simple (you can use every list function on text) and others surprising (a list of numbers can print as text). This lesson shows how to print values, how strings really work and which module to reach for when you manipulate text.

Printing with io:format

io:format(Format, Args) is the workhorse. The first argument is a format string with control sequences that start with a tilde (~); the second is a list with one value per sequence.

ERLANG
1> io:format("Hello, ~s!~n", ["Ada"]).
Hello, Ada!
ok
2> io:format("~p squared is ~p~n", [4, 16]).
4 squared is 16
ok
3> io:format("~.2f~n", [3.14159]).
3.14
ok

The most useful sequences:

Sequence Meaning
~s A string (or iolist or binary) as text
~p Pretty-print any term, with line breaks for big values
~w Write any term on one line, no pretty-printing
~n Newline
~d An integer
~f A float with 6 decimals; ~.2f gives 2
~e A float in scientific notation
~c A single character from its code
~~ A literal tilde
~ts A string with Unicode characters

Width and padding go between the tilde and the letter: ~10s right-aligns in 10 columns, ~-10s left-aligns, and ~10.2f combines width and precision.

ERLANG
1> io:format("~-8s|~6.2f|~n", ["tea", 3.5]).
tea     |  3.50|
ok
2> io:format("~p~n", [#{name => "Ada", age => 36}]).
#{age => 36,name => "Ada"}
ok

If the number of arguments does not match the control sequences, you get a badarg error. Always pass a list, even for one value: io:format("~p~n", [X]), not io:format("~p~n", X).

For debugging, io:format("~p~n", [Value]) is the habit of every Erlang programmer. io:fwrite/2 is an alias of io:format/2.

Strings are lists

ERLANG
1> "abc".
"abc"
2> [97, 98, 99].
"abc"
3> hd("abc").
97
4> "abc" ++ "def".
"abcdef"
5> length("hรฉllo").
5
6> [8364].
[8364]

The shell prints a list of integers as a string when every number is a printable character code. [97, 98, 99] and "abc" are the very same value. In the last example, 8364 (the euro sign) is not Latin-1 printable, so the shell shows the numbers. Erlang uses Unicode code points as the integers, so ~ts and io:format("~ts~n", [[8364]]) handle it correctly.

A list of integers that accidentally looks printable shows up as text, which can be confusing when debugging. Use ~w or io:format("~p", [Value]) after setting shell:strings(false) to always see the numbers.

The string module

The string module works on text. Many functions accept either a string or a binary and return the same type.

ERLANG
1> string:uppercase("erlang").
"ERLANG"
2> string:lowercase("ERLANG").
"erlang"
3> string:trim("  hi  ").
"hi"
4> string:split("a,b,c", ",", all).
["a","b","c"]
5> string:find("hello world", "world").
"world"
6> string:length("hello").
5
7> lists:flatten(string:replace("one two", "two", "three")).
"one three"
8> lists:flatten(lists:join("-", ["a", "b"])).
"a-b"

string:replace/3 returns an iolist, a nested list that is fine to print or send but not always flat, so call lists:flatten/1 when you need a flat string. string:join/2 is obsolete; use lists:join/2 as shown.

Binaries as text

Double-quoted text is a list, which uses 16 bytes (on 64-bit) per character. A binary stores raw bytes compactly, written <<"hello">>. Network and file code usually uses binaries.

ERLANG
1> <<"hello">>.
<<"hello">>
2> byte_size(<<"hello">>).
5
3> list_to_binary("hello").
<<"hello">>
4> binary_to_list(<<"hi">>).
"hi"
5> <<"a", "b">>.
<<"ab">>

Use unicode:characters_to_binary/1 and unicode:characters_to_list/1 for text with non-ASCII characters; list_to_binary only accepts values up to 255. The binaries lesson goes deeper.

Conversions

ERLANG
1> integer_to_list(42).
"42"
2> list_to_integer("42").
42
3> float_to_list(2.5, [{decimals, 1}]).
"2.5"
4> atom_to_list(hello).
"hello"
5> list_to_existing_atom("hello").
hello
6> lists:flatten(io_lib:format("~p-~p", [1, 2])).
"1-2"

io_lib:format/2 builds a string instead of printing it, and returns an iolist that you flatten.

Stand-ins in JavaScript

These show the "string is a list of codes" idea and a small format function. They are not Erlang.

JS Stand-in: a string is a list of integers (JavaScript, not Erlang)

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

No output.

JS Stand-in: a tiny io:format (JavaScript, not Erlang)

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the string "abc" in Erlang?

    Double-quoted text is a list of character codes, so list functions work on it.
  2. 2. Which control sequence prints any term in a readable, pretty-printed form?

    ~p pretty-prints a term, and is the usual choice for debugging.
  3. 3. What is wrong with io:format("pn", 42)?

    The second argument is always a list of values: io:format("pn", [42]).
  4. 4. What does <<"hi">> create?

    <<...>> is binary syntax. A text literal inside it becomes bytes.

Summary

  • io:format(Format, [Args]) prints; ~p pretty-prints, ~s strings, ~w raw terms, ~n newline, ~.2f floats.
  • Strings are lists of Unicode code points, so "abc" and [97,98,99] are the same value.
  • The string module covers trimming, splitting, case and search; results can be iolists, so flatten when needed.
  • Binaries (<<"text">>) store bytes compactly and are the usual choice for I/O.
  • io_lib:format/2 builds text without printing it.

Next: Functions and Clauses