Search code examples
stringjuliaquotesstring-literals

Single vs Double quotes in Julia


What is the difference between single quotes and double quotes in Julia?

Unlike Python, for strings, it doesn't allow single quotes:

> s = 'abc'
syntax: invalid character literal
> s = "abc"
> print(s)
abc

But when trying to single quote a double quote, it's allowed:

> s = '"'
> print(s)
"

What is the single quote use for in Julia? Is there documentation like Python's PEP to explain for reason why single quotes are not used?


Solution

  • Think of it like in C/C++; a single quote makes a Char, while double quotes make a String (see, e.g., here).

    julia> c = 'a'
    'a'
    julia> typeof(c)
    Char
    julia> s = "a"
    "a"
    julia> typeof(s)
    String
    julia> s = "ab"
    "ab"
    julia> typeof(s)
    String
    

    In Python we just use a string of length one as characters, but Julia distinguishes between them, and so we get

    julia> typeof("abc"[1:1])
    String    
    julia> typeof("abc"[1])
    Char
    

    even though in Python we have

    >>> type("abc"[0:1])
    <type 'str'>
    >>> type("abc"[0])
    <type 'str'>