DEV Community

Daniil Baturin
Daniil Baturin

Posted on

Multi-line string literals

Python

I suppose most people know that Python allows writing multi-line string literals in triple quotes. This feature relatively hard to miss because it's used in docstrings.

def hello():
  """ Prints a greeting """
  print("hello world")
Enter fullscreen mode Exit fullscreen mode

Using it for variables is also common.

s = '''
hello
world
'''

print(s)
Enter fullscreen mode Exit fullscreen mode

All in all, it's an easily discoverable feature.

Lua

It's less widely known that Lua supports multi-line strings because it uses unusual delimiters: double square brackets.

s = [[
hello
world
]]

print(s)
Enter fullscreen mode Exit fullscreen mode

Let's see if it works:

$ lua ./test.lua 
hello
world

Enter fullscreen mode Exit fullscreen mode

Once you remember the delimiter, it's not harder to use than Python's triple quotes.

This syntax is also used by the TOML serialization format.

OCaml

OCaml's approach is the easiest of all. However, it's also the least easily discoverable.

To write a multi-line string, you... need not do anything special. You can use add line breaks to normal strings and the lexer will understand them.

let s = "
hello
world
"

let () = Printf.printf "%s" s
Enter fullscreen mode Exit fullscreen mode

Let's test it:

 ocamlopt -o test ./test.ml 

$ ./test 

hello
world

Enter fullscreen mode Exit fullscreen mode

Top comments (0)