Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 40 · Basics

Strings and Characters

Learn Julia strings and chars: String vs Char, byte-based indexing, interpolation, join, split, replace, regular expressions and Unicode handling.

Text in Julia is built from two types: String for sequences of characters and Char for a single one. Julia strings are UTF-8 encoded Unicode, which means "héllo" and "日本語" work out of the box. They also come with one surprise that trips up almost everyone: string indexing counts bytes, not characters.

This lesson covers the two types, indexing and why it works the way it does, the everyday functions for building and splitting text, and the basics of regular expressions. Julia code is read-only here, with output in comments. Python stand-ins let you reproduce the UTF-8 byte behavior.

String and Char

Double quotes make a String, single quotes make a Char:

JULIA
s = "hello"
c = 'h'

typeof(s)    # String
typeof(c)    # Char
'h' == "h"   # false: a Char and a String are different types

Chars are numbers in disguise. You can convert between a character and its Unicode code point, and do a little arithmetic:

JULIA
Int('a')        # 97
Char(98)        # 'b'
'a' + 1         # 'b'
'z' - 'a'       # 25
isletter('x')   # true
isdigit('7')    # true
uppercase('q')  # 'Q'

For multi-line text use triple quotes. They keep the newlines and ignore a leading newline directly after the opening quotes:

JULIA
poem = """
Roses are red,
Violets are blue.
"""

For text with many backslashes, such as Windows paths, a raw"..." string disables escapes: raw"C:\users\ada".

Building strings

Concatenate with *, repeat with ^, and interpolate with $:

JULIA
given = "Ada"
family = "Lovelace"

given * " " * family               # "Ada Lovelace"
"-" ^ 10                           # "----------"
"Name: $given $family"             # "Name: Ada Lovelace"
"Sum: $(1 + 2)"                    # "Sum: 3"
string("a", 1, :b)                 # "a1b"

string converts each argument to text and joins them, which is handy for mixed values. join glues the elements of a collection together with a separator:

JULIA
join(["red", "green", "blue"], ", ")        # "red, green, blue"
join(["red", "green", "blue"], ", ", " or ")  # "red, green or blue"

Common string functions

JULIA
s = "Hello, Julia!"

length(s)                    # 13
uppercase(s)                 # "HELLO, JULIA!"
lowercase(s)                 # "hello, julia!"
startswith(s, "Hello")       # true
endswith(s, "!")             # true
occursin("Julia", s)         # true
replace(s, "Julia" => "World")   # "Hello, World!"
reverse("abc")               # "cba"
strip("  padded  ")          # "padded"
repeat("ab", 3)              # "ababab"
findfirst("Julia", s)        # 8:12

Strings are immutable. Functions like uppercase and replace return new strings and never change the original. The pair "Julia" => "World" is a Pair, the same notation used by dictionaries.

Splitting

JULIA
split("a,b,c", ",")          # ["a", "b", "c"]
split("one two  three")      # ["one", "two", "three"] (splits on whitespace)
split("a,b,,c", ",")         # ["a", "b", "", "c"]
split("a,b,,c", ","; keepempty=false)   # ["a", "b", "c"]
parse(Int, "42")             # 42
parse(Float64, "3.5")        # 3.5
tryparse(Int, "oops")        # nothing

split returns a vector of SubString values, which are lightweight views into the original string. tryparse returns nothing instead of throwing, so it is the safe choice for user input.

Text toolbox

split Break text into pieces.
join Glue pieces together.
replace Swap one part for another.
occursin Search for a substring.

All of them return new values. Strings never change in place.

1 / 2

Indexing counts bytes

Julia strings are stored as UTF-8. ASCII letters take one byte, but characters such as é take two, 日 takes three and many emoji take four. Indexing with s[i] uses the byte position:

JULIA
s = "héllo"

length(s)     # 5   number of characters
sizeof(s)     # 6   number of bytes
s[1]          # 'h'
s[2]          # 'é'
s[3]          # StringIndexError: invalid index [3], valid nearby indices [2]/[4]
s[4]          # 'l'
collect(eachindex(s))   # [1, 2, 4, 5, 6]

Index 3 is the middle of the two bytes of é, so it is not a valid start of a character and Julia throws instead of returning half a letter. To loop over characters, loop over the string itself instead of indices:

JULIA
for c in "héllo"
    print(c, " ")
end
# h é l l o

Use nextind(s, i) and prevind(s, i) to step to the next or previous valid index, and first(s, 3) or last(s, 3) for the first or last characters. Slicing with a range works with valid byte indices: s[1:2] is "hé". When you need the n-th character, convert to a vector once with collect(s)[n], accepting the cost.

The reason for this design is speed: byte indexing is constant time, and ASCII text (the common case) behaves exactly as you would expect.

This stand-in shows the same layout using Python's UTF-8 encoding. Python normally hides bytes from you, so here you look at them directly.

Python Characters versus bytes

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

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Julia the check happens for you with StringIndexError; here we trigger the equivalent failure by decoding half of the two-byte character.

Regular expressions

A regex literal is written r"...". The main tools are occursin, match, eachmatch and replace:

JULIA
occursin(r"\d+", "order 66")             # true

m = match(r"(\d+)-(\d+)", "range 10-20")
m.match        # "10-20"
m.captures     # ["10", "20"]
m[1]           # "10"

collect(eachmatch(r"\d+", "a1 b22 c333"))   # three RegexMatch objects
[m.match for m in eachmatch(r"\d+", "a1 b22 c333")]   # ["1", "22", "333"]

replace("2024-05-17", r"(\d+)-(\d+)-(\d+)" => s"\3/\2/\1")   # "17/05/2024"

match returns nothing when there is no match, so check before using the result. The s"..." string in the replacement uses \1, \2 for captured groups. Named groups work too: r"(?<year>\d{4})", accessed as m[:year].

Julia's regexes use the PCRE2 library, so patterns look like those in Perl, Python and PHP. Raw strings are the default for r"..." so you rarely need to double backslashes.

The same match, in Python, for comparison:

Python Capture groups (Python equivalent)

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

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Unicode and symbols

Because Julia source files are UTF-8, identifiers and strings can hold any language. You can enter special characters in escapes or by Tab completion:

JULIA
"\u00e9"      # "é"
"\U1F600"     # an emoji
"tab\there"   # a tab inside the string

Normalization and case folding for international text live in the Unicode standard library: Unicode.normalize("é", :NFD) splits into a letter plus an accent. For most programs uppercase and lowercase are enough.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What is the type of 'a'?

    Single quotes create a Char. Double quotes create a String, and the two are different types.
  2. 2. Which operator concatenates two strings?

    Julia joins strings with * and repeats them with ^. string(a, b) and interpolation also work.
  3. 3. For s = "héllo", what does s[3] do?

    Indexing is by byte position. é occupies bytes 2 and 3, so only index 2 starts a character.
  4. 4. How can you safely turn user text into an integer without an exception?

    tryparse returns nothing when the text is not a valid number, while parse throws an ArgumentError.
  5. 5. What does match(r"(\d+)", "abc") return?

    match returns nothing when the pattern does not match, so check the result before reading m.captures.

Summary

  • String uses double quotes, Char uses single quotes, and strings are immutable UTF-8.
  • Build text with *, ^, $ interpolation, string and join.
  • split, replace, occursin, startswith, uppercase and friends return new values.
  • s[i] indexes by byte; use for c in s, eachindex, nextind or collect for characters.
  • parse throws on bad input while tryparse returns nothing.
  • Regexes are written r"..." and used with match, eachmatch and replace.

Next, learn how to make decisions and repeat work in Control Flow.